package org.jeecg.modules.wlhy.shipping.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.api.controller.ShippingVo;
import org.jeecg.modules.api.wlhy.customer.HyShippingNoteTongJiDTO;
import org.jeecg.modules.middleware.rabbitmq.gen.EnumGenHandler;
import org.jeecg.modules.middleware.rabbitmq.gen.GenMqUtil;
import org.jeecg.modules.paycenter.enums.BillTypeEnum;
import org.jeecg.modules.paycenter.service.BillService;
import org.jeecg.modules.third.amap.dto.MapDirectionDTO;
import org.jeecg.modules.third.amap.service.AmapService;
import org.jeecg.modules.wlhy.bill.entity.HyBill;
import org.jeecg.modules.wlhy.bill.service.IHyBillService;
import org.jeecg.modules.wlhy.company.entity.HyCompany;
import org.jeecg.modules.wlhy.company.entity.HyCompanyConfig;
import org.jeecg.modules.wlhy.company.service.IHyCompanyConfigService;
import org.jeecg.modules.wlhy.company.service.IHyCompanyService;
import org.jeecg.modules.wlhy.customer.dto.HyCustomerAddressRecvZybDTO;
import org.jeecg.modules.wlhy.customer.dto.HyCustomerAddressSendZybDTO;
import org.jeecg.modules.wlhy.customer.entity.*;
import org.jeecg.modules.wlhy.customer.service.*;
import org.jeecg.modules.wlhy.hyarea.service.IHyAreaService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hydriverbank.entity.HyDriverBank;
import org.jeecg.modules.wlhy.hydriverbank.service.IHyDriverBankService;
import org.jeecg.modules.wlhy.hyevent.event.DeBangEvent;
import org.jeecg.modules.wlhy.hyevent.event.PicDownloadEvent;
import org.jeecg.modules.wlhy.hyinsurance.dto.InsuranceApplyDto;
import org.jeecg.modules.wlhy.hyinsurance.entity.InsuranceApplyRecord;
import org.jeecg.modules.wlhy.hyinsurance.service.InsuranceApplyRecordService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.hyzyb.constant.ZybShippingTypeEnum;
import org.jeecg.modules.wlhy.hyzyb.dto.FenceTriggerDTO;
import org.jeecg.modules.wlhy.hyzyb.dto.ShippingFenceDTO;
import org.jeecg.modules.wlhy.hyzyb.dto.ShippingFenceTriggerDTO;
import org.jeecg.modules.wlhy.hyzyb.entity.HyZybStatus;
import org.jeecg.modules.wlhy.hyzyb.service.IHyZybService;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.order.entity.HyOrderPrice;
import org.jeecg.modules.wlhy.order.entity.HyOrderReceiveAddress;
import org.jeecg.modules.wlhy.order.entity.HyOrderSendAddress;
import org.jeecg.modules.wlhy.order.service.IHyOrderPriceService;
import org.jeecg.modules.wlhy.order.service.IHyOrderReceiveAddressService;
import org.jeecg.modules.wlhy.order.service.IHyOrderSendAddressService;
import org.jeecg.modules.wlhy.order.service.IHyOrderService;
import org.jeecg.modules.wlhy.report.ShippingNoteApiAlct56Service;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.shipping.constant.ShippingStatus;
import org.jeecg.modules.wlhy.shipping.dto.ImportUpdateShippingNoteDTO;
import org.jeecg.modules.wlhy.shipping.dto.LnTaxShippingNoteDTO;
import org.jeecg.modules.wlhy.shipping.entity.*;
import org.jeecg.modules.wlhy.shipping.mapper.HyShippingNoteMapper;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteReceiveAddressService;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteSendAddressService;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.shipping.vo.ZybShippingNoteVO;
import org.jeecg.modules.wlhy.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.io.File;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HyShippingNoteServiceImpl extends ServiceImpl<HyShippingNoteMapper, HyShippingNote> implements IHyShippingNoteService {

    private static final Logger LOGGER = LoggerFactory.getLogger(HyShippingNoteServiceImpl.class);

    @Autowired
    private IHyOrderService orderService;

    @Autowired
    private IHyCustomerService customerService;

    @Autowired
    private IHyDriverService driverService;

    @Autowired
    private IHyDriverBankService driverBankService;

    @Autowired
    private IHyVehicleService vehicleService;

    @Autowired
    private IHyCompanyService companyService;

    @Autowired
    private IHyCompanyConfigService companyConfigService;

    @Autowired
    private IHyCustomerCompanyService hyCustomerCompanyService;
    @Autowired
    private IHyCustomerConfigService hyCustomerConfigService;

    @Autowired
    private IHyShippingNoteSendAddressService hyShippingNoteSendAddressService;
    @Autowired
    private IHyShippingNoteReceiveAddressService hyShippingNoteReceiveAddressService;

    @Autowired
    private IHyOrderSendAddressService hyOrderSendAddressService;

    @Autowired
    private IHyOrderReceiveAddressService hyOrderReceiveAddressService;

    @Autowired
    private IHyBillService hyBillService;

    @Autowired
    private IHyAreaService hyAreaService;

    @Autowired
    private CodeUtil codeUtil;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Value(value = "${local.domain:}")
    private String serviceName;

    @Autowired
    private IHyOrderPriceService hyOrderPriceService;

    @Autowired
    private IHySettingService hySettingService;

    @Autowired
    private IHyDriverService hyDriverService;

    @Autowired
    private IHyOrderService hyOrderService;

    @Autowired
    private BillService billService;

    @Autowired
    private IHyZybService zybService;

    @Autowired
    private ShippingNoteApiAlct56Service shippingNoteApiAlct56Service;

    @Autowired
    private InsuranceApplyRecordService insuranceApplyRecordService;



    @Autowired
    private IHyCustomerAddressSendService customerAddressSendService;

    @Autowired
    private IHyCustomerAddressReceiveService customerAddressReceiveService;
    @Autowired
    private UserUtil userUtil;

    @Autowired
    private AmapService amapService;

    @Override
    public int getCountByDate(String dateString) {
        return baseMapper.getCountByDate(dateString);
    }

    public void checkCalcData(HyShippingNote hyShippingNote){
        HyStatusCheckUtil.checkPayType(hyShippingNote.getPayType());
        //1单价4包车
        HyStatusCheckUtil.checkShippingType(hyShippingNote.getShippingType());
        //亏损方式
        HyStatusCheckUtil.checkLossType(hyShippingNote.getLossType());

        if (hyShippingNote.getGoodsWeightLoading() == null) {
            throw new JeecgBootException("装货量不能为空,请核实运单信息");
        }
        if (hyShippingNote.getGoodsWeightUnloading() == null) {
            throw new JeecgBootException("卸货量不能为空,请核实运单信息");
        }
        if (hyShippingNote.getShippingUnitPrice() == null) {
            throw new JeecgBootException("运费单价不能为空,请核实运单信息");
        }
        if (hyShippingNote.getLossGoodsUnitPrice() == null) {
            throw new JeecgBootException("亏损货物单价不能为空,请核实运单信息");
        }
        if (hyShippingNote.getLossProportion() == null) {
            throw new JeecgBootException("亏损免赔数不能为空,请核实运单信息");
        }
    }

    //核算运费
    @Override
    public void calcCoss(HyShippingNote hyShippingNote) {
        this.checkCalcData(hyShippingNote);
        HyOrder hyOrder = hyOrderService.getById(hyShippingNote.getOrderId());

        HyCustomerCompany customerCompany = hyCustomerCompanyService.getById(hyOrder.getCostServiceId());
        if (customerCompany == null) {
            customerCompany = hyCustomerCompanyService.getByCustomerId(hyShippingNote.getCustomerId());
            if(customerCompany==null){
                throw new JeecgBootException("未找到签约公司信息信息");
            }
        }
        //服务费是否开票
        String izServiceOpenInvoicing = customerCompany.getIzServiceOpenInvoicing();
        if (!"1".equals(izServiceOpenInvoicing) && !"0".equals(izServiceOpenInvoicing)) {
            izServiceOpenInvoicing = "1";
        }
        //设置服务费是否开票
        hyShippingNote.setIzServiceOpenInvoicing(izServiceOpenInvoicing);
        //设置信息费是否开票
//        hyShippingNote.setIzInformationFeeOpenInvoicing(customerCompany.getIzInformationFeeOpenInvoicing());
        BigDecimal companyCostServicePercent = customerCompany.getCostServicePercent();
        if (companyCostServicePercent == null) {
            throw new JeecgBootException("服务费比例错误");
        }
        HyCustomerConfig customerConfig = hyCustomerConfigService.getByCustomerId(hyShippingNote.getCustomerId());
        BigDecimal shippingSubFee = hyBillService.getShippingSubFee(hyShippingNote.getId());
        String orderMode = hyShippingNote.getOrderMode();
        if ("1".equals(orderMode)) {
            hyShippingNote.setAgentCostPay(BigDecimal.ZERO);
            hyShippingNote.setAgentCostPayShipping(BigDecimal.ZERO);
            hyShippingNote.setAgentCostPayTotal(BigDecimal.ZERO);
            HyCalcFeeUtil.calcOrderMode1(hyShippingNote, customerCompany, customerConfig, shippingSubFee);
        }else if ("3".equals(orderMode)) {
            HyCalcFeeUtil.calcOrderMode3(hyShippingNote, customerCompany, customerConfig, shippingSubFee);
        }else if ("4".equals(orderMode)) {
            hyShippingNote.setAgentCostPay(BigDecimal.ZERO);
            hyShippingNote.setAgentCostPayShipping(BigDecimal.ZERO);
            hyShippingNote.setAgentCostPayTotal(BigDecimal.ZERO);
            HyCalcFeeUtil.calcOrderMode4(hyShippingNote, customerCompany, customerConfig, shippingSubFee);
        }
    }

    @Override
    public HyShippingNote queryByShippingNoteNumber(String shippingNoteNumber) {
        return baseMapper.queryByShippingNoteNumber(shippingNoteNumber);
    }

    @Override
    public List<ShippingMonthTotalDTO> getShippingMonthTotal(String customerId, String startMonth, String endMonth) {
        return baseMapper.getShippingMonthTotal(customerId, startMonth, endMonth);
    }

    @Override
    public IPage<HyShippingNoteDTO> getPageList(Page<HyShippingNoteDTO> page,
                                                QueryWrapper<HyShippingNoteDTO> queryWrapper) {
        IPage<HyShippingNoteDTO> pageList = baseMapper.getPageList(page, queryWrapper);
        return pageList;
    }

    @Override
    public IPage<LnTaxShippingNoteDTO> getLnTaxPageList(Page<LnTaxShippingNoteDTO> page,
                                                        QueryWrapper<LnTaxShippingNoteDTO> queryWrapper) {
        IPage<LnTaxShippingNoteDTO> pageList = baseMapper.getLnTaxPageList(page, queryWrapper);
        return pageList;
    }

    @Override
    public IPage<HyShippingNoteDTO> getPageCheckList(Page<HyShippingNoteDTO> page,
                                                QueryWrapper<HyShippingNoteDTO> queryWrapper) {
        IPage<HyShippingNoteDTO> pageList = baseMapper.getPageCheckList(page, queryWrapper);
        return pageList;
    }


    /**
     * 导入运单
     *
     * @param shippingNotes
     */
    @Override
    @Transactional
    public void saveBatchShippingNote(List<HyShippingNote> shippingNotes) {

        if (CollectionUtils.isNotEmpty(shippingNotes)) {

            List<String> orderIds = shippingNotes.stream().map(
                    item -> item.getOrderId()
            ).distinct().filter(Objects::nonNull).collect(Collectors.toList());

            QueryWrapper queryWrapperSendAddress = new QueryWrapper();
            queryWrapperSendAddress.in("order_id", orderIds);
            List<HyOrderSendAddress> orderSendAddressList = hyOrderSendAddressService.list(queryWrapperSendAddress);

            QueryWrapper queryWrapperReceiveAddress = new QueryWrapper();
            queryWrapperReceiveAddress.in("order_id", orderIds);
            List<HyOrderReceiveAddress> orderReceiveAddressList = hyOrderReceiveAddressService.list(queryWrapperReceiveAddress);

            this.saveBatch(shippingNotes);
            //查询货源
            log.info("导入运单扩展数据, {}", shippingNotes.size());
            List<HyShippingNoteSendAddress> hyShippingNoteSendAddressList = new ArrayList<>();
            List<HyShippingNoteReceiveAddress> hyShippingNoteReceiveAddressList = new ArrayList<>();
            int index = 1;
            List<HyBill> hyBillList = new ArrayList<>();
            for (HyShippingNote shippingNote : shippingNotes) {
                //如果是上报过的运单，这里就不用存地址了
                if (StrUtil.isEmpty(shippingNote.getUploadStatus())) {

                    //只匹配当前运单的收发货地址
                    List<HyOrderSendAddress> orderSendAddress = orderSendAddressList.stream().filter(s->s.getOrderId().equals(shippingNote.getOrderId())).collect(Collectors.toList());
                    List<HyOrderReceiveAddress> orderReceiveAddress = orderReceiveAddressList.stream().filter(r->r.getOrderId().equals(shippingNote.getOrderId())).collect(Collectors.toList());

                    List<HyShippingNoteSendAddress> hyShippingNoteSendAddress = orderSendAddress.stream().map(
                            item -> OrderSendAddressTOOShippingNoteSendAddress(item, shippingNote.getId())
                    ).collect(Collectors.toList());
                    hyShippingNoteSendAddressList.addAll(hyShippingNoteSendAddress);

                    List<HyShippingNoteReceiveAddress> hyShippingNoteReceiveAddress = orderReceiveAddress.stream().map(
                            item -> OrderReceiveAddressTOOShippingNoteReceiveAddress(item, shippingNote.getId())
                    ).collect(Collectors.toList());
                    hyShippingNoteReceiveAddressList.addAll(hyShippingNoteReceiveAddress);
                }

                if("4".equals(shippingNote.getShippingPayStatus()) || "6".equals(shippingNote.getShippingPayStatus())){
                    HyBill hyBill = billService.createBill(shippingNote, BillTypeEnum.PAY ,null , null);
                    if("6".equals(shippingNote.getShippingPayStatus())){
                        hyBill.setPayStatus("6");
                    }
                    hyBillList.add(hyBill);
                }
                log.info("导入运单Bill扩展数据, {}", index);
                index++;
            }
            if (CollectionUtils.isNotEmpty(hyShippingNoteSendAddressList)) {
                hyShippingNoteSendAddressService.saveBatch(hyShippingNoteSendAddressList);
            }
            if (CollectionUtils.isNotEmpty(hyShippingNoteReceiveAddressList)) {
                hyShippingNoteReceiveAddressService.saveBatch(hyShippingNoteReceiveAddressList);
            }
            if (CollectionUtils.isNotEmpty(hyBillList)) {
                hyBillService.saveBatch(hyBillList);
            }
        }

    }

    @Override
    public List<ImportShippingNoteDTO> queryImportShippingNoteDTOS(List<ImportShippingNoteDTO> listShippingNote) {
        //查询公司
        List<String> companyNames = listShippingNote.stream().map(
                item -> item.getCompanyName().trim()
        ).distinct().filter(Objects::nonNull).collect(Collectors.toList());

        QueryWrapper queryWrapperCompanyName = new QueryWrapper();
        queryWrapperCompanyName.in("company_name", companyNames);
        List<HyCompany> companyNameList = companyService.list(queryWrapperCompanyName);
        if (companyNameList.size() != companyNames.size()) {

            List<String> dbCompanyNames = companyNameList.stream().map(
                    item -> item.getCompanyName()
            ).collect(Collectors.toList());

            String filterCompanyNames = companyNames.stream()
                    .filter(item -> !dbCompanyNames.contains(item))
                    .collect(Collectors.joining(",", "(", ")"));
            throw new JeecgBootException(filterCompanyNames + "公司数据信息有误");
        }

        Map<String, String> companyNameMaps = companyNameList.stream().collect(
                Collectors.toMap(HyCompany::getCompanyName, HyCompany::getId, (key1, key2) -> key2)
        );

        //查询货主
        List<String> customerNames = listShippingNote.stream().map(
                item -> item.getCustomerName().trim()
        ).distinct().filter(Objects::nonNull).collect(Collectors.toList());

        QueryWrapper queryWrapperCustomerName = new QueryWrapper();
        queryWrapperCustomerName.in("customer_name", customerNames);
        queryWrapperCustomerName.eq("iz_used", 1);
        List<HyCustomer> customerNameList = customerService.list(queryWrapperCustomerName);
        if (customerNames.size() != customerNameList.size()) {

            List<String> dbCustomerNames = customerNameList.stream().map(
                    item -> item.getCustomerName()
            ).collect(Collectors.toList());

            String filterCustomerNames = customerNames.stream()
                    .filter(item -> !dbCustomerNames.contains(item))
                    .collect(Collectors.joining(",", "(", ")"));
            log.warn("查询到系统中已有货主数据{}, 实际导入的货主数据{}", JSONUtil.toJsonStr(dbCustomerNames), JSONUtil.toJsonStr(customerNames));
            throw new JeecgBootException(filterCustomerNames + "货主数据信息有误");
        }

        Map<String, String> customerNameMaps = customerNameList.stream().collect(
                Collectors.toMap(HyCustomer::getCustomerName, HyCustomer::getId, (key1, key2) -> key2)
        );

        //查询货源
        List<String> orderNums = listShippingNote.stream().map(
                item -> item.getOrderNum().trim()
        ).distinct().filter(Objects::nonNull).collect(Collectors.toList());

        QueryWrapper queryWrapperOrder = new QueryWrapper();
        queryWrapperOrder.in("order_num", orderNums);
        List<HyOrder> orderNumList = orderService.list(queryWrapperOrder);

        if (orderNums.size() > orderNumList.size()) {
            log.warn("导入运单所属货源数大于总货源数，不匹配, {} {}", orderNums.size(), orderNumList.size());
            List<String> dbOrderNums = orderNumList.stream().map(
                    item -> item.getOrderNum()
            ).collect(Collectors.toList());

            List<String> filterOrderNums = orderNums.stream()
                    .filter(item -> !dbOrderNums.contains(item))
                    .collect(Collectors.toList());

            throw new JeecgBootException(JSONUtil.toJsonStr(filterOrderNums) + ",货源数据信息有误");
        }

        Map<String, HyOrder> orderNumMaps = orderNumList.stream().collect(
                Collectors.toMap(HyOrder::getOrderNum, Function.identity(), (key1, key2) -> key2)
        );


        //查询司机
        List<String> telephones = listShippingNote.stream().map(
                item -> item.getTelephone().trim()
        ).distinct().filter(Objects::nonNull).collect(Collectors.toList());


        int section = 10;
        List<HyDriver> driverList = new LinkedList<>();
        for (int index = 0, end = 0; index < telephones.size(); index = end) {
            end = (end + section) <= telephones.size() ? end + section : telephones.size();
            if (index < end) {
                QueryWrapper<HyDriver> querydriverWrapper = new QueryWrapper();
                querydriverWrapper.in("telephone", telephones.subList(index, end));
                driverList.addAll(driverService.list(querydriverWrapper));
            }
        }


        if (telephones.size() != driverList.size()) {
            List<String> dbTelephones = driverList.stream().map(
                    item -> item.getTelephone()
            ).collect(Collectors.toList());

            String filterTelephones = telephones.stream()
                    .filter(item -> !dbTelephones.contains(item))
                    .collect(Collectors.joining(",", "(", ")"));

            throw new JeecgBootException(filterTelephones + "司机手机号数据信息有误");
        }

        Map<String, HyDriver> telephoneMaps = driverList.stream().collect(
                Collectors.toMap(HyDriver::getTelephone,  Function.identity(), (key1, key2) -> key2)
        );

        //查询车辆
        List<String> vehicleNumbers = listShippingNote.stream().map(
                item -> item.getVehicleNumber().trim()
        ).distinct().filter(Objects::nonNull).collect(Collectors.toList());


        int sectionv = 10;
        List<HyVehicle> vehicleList = new LinkedList<>();
        for (int index = 0, end = 0; index < vehicleNumbers.size(); index = end) {
            end = (end + sectionv) <= vehicleNumbers.size() ? end + sectionv : vehicleNumbers.size();
            if (index < end) {
                QueryWrapper<HyVehicle> queryWrapperVehicle = new QueryWrapper();
                queryWrapperVehicle.in("vehicle_number", vehicleNumbers.subList(index, end));
                vehicleList.addAll(vehicleService.list(queryWrapperVehicle));
            }
        }


        if (vehicleNumbers.size() != vehicleList.size()) {
            List<String> dbVehicleNumbers = vehicleList.stream().map(
                    item -> item.getVehicleNumber()
            ).collect(Collectors.toList());

            String filterVehicleNumbers = vehicleNumbers.stream()
                    .filter(item -> !dbVehicleNumbers.contains(item))
                    .collect(Collectors.joining(",", "(", ")"));

            throw new JeecgBootException(filterVehicleNumbers + "车辆数据信息有误");
        }

        Map<String, String> vehicleNumMaps = vehicleList.stream().collect(
                Collectors.toMap(HyVehicle::getVehicleNumber, HyVehicle::getId, (key1, key2) -> key2)
        );

        //查询司机银行卡
        List<String> bankNums = listShippingNote.stream().filter(item -> StrUtil.isNotEmpty(item.getBankNum())).map(
                item -> item.getBankNum().trim()
        ).distinct().filter(Objects::nonNull).collect(Collectors.toList());

        Map<String, String> bankNumMaps = new HashMap<>();
        if (CollectionUtils.isNotEmpty(bankNums)) {
            QueryWrapper queryWrapperBankNum = new QueryWrapper();
            queryWrapperBankNum.in("bank_num", bankNums);
            List<HyDriverBank> driverBanks = driverBankService.list(queryWrapperBankNum);
            bankNumMaps = driverBanks.stream().collect(Collectors.toMap(HyDriverBank::getBankNum, HyDriverBank::getId, (key1, key2) -> key2));

        }
        for (ImportShippingNoteDTO item : listShippingNote) {
            item.setVehicleId(vehicleNumMaps.get(item.getVehicleNumber().trim()));
            item.setDriverId(telephoneMaps.get(item.getTelephone().trim()).getId());
            item.setDriver(telephoneMaps.get(item.getTelephone().trim()));
            item.setOrderId(orderNumMaps.get(item.getOrderNum().trim()).getId());
            item.setHyOrder(orderNumMaps.get(item.getOrderNum().trim()));
            item.setCustomerId(customerNameMaps.get(item.getCustomerName().trim()));
            item.setCompanyId(companyNameMaps.get(item.getCompanyName().trim()));

            if (MapUtils.isNotEmpty(bankNumMaps) && StrUtil.isNotEmpty(item.getBankNum())) {
                item.setDriverBankId(bankNumMaps.get(item.getBankNum().trim()));
            } else {
                item.setDriverBankId(StringUtils.EMPTY);
            }
        }
        return listShippingNote;
    }

    public static HyShippingNoteReceiveAddress OrderReceiveAddressTOOShippingNoteReceiveAddress(
            HyOrderReceiveAddress hyOrderReceiveAddress, String shippingNoteId) {
        if (hyOrderReceiveAddress == null || StringUtils.isBlank(shippingNoteId)) {
            return null;
        }
        HyShippingNoteReceiveAddress hyShippingNoteReceiveAddress = new HyShippingNoteReceiveAddress();

        hyShippingNoteReceiveAddress.setShippingId(shippingNoteId);
        hyShippingNoteReceiveAddress.setOrderId(hyOrderReceiveAddress.getOrderId());
        hyShippingNoteReceiveAddress.setCustomerId(hyOrderReceiveAddress.getCustomerId());
        hyShippingNoteReceiveAddress.setIzDest(hyOrderReceiveAddress.isIzDest());
        hyShippingNoteReceiveAddress.setAddressReceiveId(hyOrderReceiveAddress.getAddressReceiveId());
        hyShippingNoteReceiveAddress.setReceiveDate(hyOrderReceiveAddress.getReceiveDate());
        hyShippingNoteReceiveAddress.setReceiveAddressName(hyOrderReceiveAddress.getReceiveAddressName());
        hyShippingNoteReceiveAddress.setReceiveLongitude(hyOrderReceiveAddress.getReceiveLongitude());
        hyShippingNoteReceiveAddress.setReceiveLatitude(hyOrderReceiveAddress.getReceiveLatitude());
        hyShippingNoteReceiveAddress.setReceiveAddress(hyOrderReceiveAddress.getReceiveAddress());
        hyShippingNoteReceiveAddress.setReceiveAreaCode(hyOrderReceiveAddress.getReceiveAreaCode());
        hyShippingNoteReceiveAddress.setReceiveContactName(hyOrderReceiveAddress.getReceiveContactName());
        hyShippingNoteReceiveAddress.setReceiveContactTel(hyOrderReceiveAddress.getReceiveContactTel());
        hyShippingNoteReceiveAddress.setRemark(hyOrderReceiveAddress.getRemark());
        hyShippingNoteReceiveAddress.setSortNum(hyOrderReceiveAddress.getSortNum());
        return hyShippingNoteReceiveAddress;
    }

    public static HyShippingNoteSendAddress OrderSendAddressTOOShippingNoteSendAddress(
            HyOrderSendAddress hyOrderSendAddress, String shippingNoteId) {
        if (hyOrderSendAddress == null || StringUtils.isBlank(shippingNoteId)) {
            return null;
        }
        HyShippingNoteSendAddress hyShippingNoteSendAddress = new HyShippingNoteSendAddress();

        hyShippingNoteSendAddress.setShippingId(shippingNoteId);
        hyShippingNoteSendAddress.setOrderId(hyOrderSendAddress.getOrderId());
        hyShippingNoteSendAddress.setCustomerId(hyOrderSendAddress.getCustomerId());
        hyShippingNoteSendAddress.setIzDest(hyOrderSendAddress.isIzDest());
        hyShippingNoteSendAddress.setAddressSendId(hyOrderSendAddress.getAddressSendId());
        hyShippingNoteSendAddress.setSendDate(hyOrderSendAddress.getSendDate());
        hyShippingNoteSendAddress.setSendAddressName(hyOrderSendAddress.getSendAddressName());
        hyShippingNoteSendAddress.setSendLongitude(hyOrderSendAddress.getSendLongitude());
        hyShippingNoteSendAddress.setSendLatitude(hyOrderSendAddress.getSendLatitude());
        hyShippingNoteSendAddress.setSendAddress(hyOrderSendAddress.getSendAddress());
        hyShippingNoteSendAddress.setSendAreaCode(hyOrderSendAddress.getSendAreaCode());
        hyShippingNoteSendAddress.setSendContactName(hyOrderSendAddress.getSendContactName());
        hyShippingNoteSendAddress.setSendContactTel(hyOrderSendAddress.getSendContactTel());
        hyShippingNoteSendAddress.setRemark(hyOrderSendAddress.getRemark());
        hyShippingNoteSendAddress.setSortNum(hyOrderSendAddress.getSortNum());
        return hyShippingNoteSendAddress;
    }


    @Override
    public HyShippingNote ImportShippingNoteDTOTOShippingNote(ImportShippingNoteDTO importShippingNoteDTO, String key) throws InterruptedException {
        if (importShippingNoteDTO == null) {
            throw new JeecgBootException("数据对象为空");
        }

        if (StringUtils.isBlank(importShippingNoteDTO.getCompanyId())) {
            throw new JeecgBootException("第" + key + "行 " + importShippingNoteDTO.getCompanyName() + " 公司信息不能为空,请先补充信息");
        }
        if (StringUtils.isBlank(importShippingNoteDTO.getCustomerId())) {
            throw new JeecgBootException("第" + key + "行 " + importShippingNoteDTO.getCustomerName() + " 货主信息不能为空,请先补充信息");
        }
        if (StringUtils.isBlank(importShippingNoteDTO.getOrderId())) {
            throw new JeecgBootException("第" + key + "行 " + importShippingNoteDTO.getOrderNum() + " 货源信息不能为空,请先补充信息");
        }
        if (StringUtils.isBlank(importShippingNoteDTO.getDriverId())) {
            throw new JeecgBootException("第" + key + "行 " + importShippingNoteDTO.getDriverName() + " 司机信息不能为空,请先补充信息");
        }
        HyDriver driver = importShippingNoteDTO.getDriver();
        if (driver == null) {
            throw new JeecgBootException("第" + key + "行 " + importShippingNoteDTO.getDriverName() + " 司机信息不能为空,请先补充信息");
        }

        if (StringUtils.isBlank(importShippingNoteDTO.getOrderId())) {
            throw new JeecgBootException("第" + key + "行 " + importShippingNoteDTO.getOrderNum() + " 货源信息不能为空,请先补充信息");
        }
        HyOrder hyOrder = importShippingNoteDTO.getHyOrder();
        if (hyOrder == null) {
            throw new JeecgBootException("第" + key + "行 " + importShippingNoteDTO.getOrderNum() + " 货源信息不能为空,请先补充信息");
        }

        HyShippingNote hyShippingNote = this.addByOrder( hyOrder,  driver ,  importShippingNoteDTO.getCompanyId());

//        if ("1".equals(hyOrder.getPayType()) && StringUtils.isBlank(importShippingNoteDTO.getDriverBankId())) {
//            throw new JeecgBootException("第" + key + "行 " + importShippingNoteDTO.getBankNum() + " 司机银行卡信息不能为空,请先补充信息");
//        }
        if (StringUtils.isBlank(importShippingNoteDTO.getVehicleId())) {
            throw new JeecgBootException("第" + key + "行 " + importShippingNoteDTO.getVehicleNumber() + " 车辆信息不能为空,请先补充信息");
        }

        if ("6".equals(importShippingNoteDTO.getShippingPayStatus()) && StringUtils.isNotBlank(importShippingNoteDTO.getPayDt())) {
            Date payDt = DateUtils.stringToDateTime(importShippingNoteDTO.getPayDt());
            if (payDt == null) {
                throw new JeecgBootException("第" + key + "行运费支付时间不正确,应为日期时间文本格式");
            }
            hyShippingNote.setDriverFee(importShippingNoteDTO.getCostPayShipping());
            hyShippingNote.setCustomerFee(importShippingNoteDTO.getCostPay());
            hyShippingNote.setPayDt(payDt);
        }
        Date createTime = DateUtils.stringToDateTime(importShippingNoteDTO.getCreateTime());

        Date statusDtSign = DateUtils.stringToDateTime(importShippingNoteDTO.getStatusDtSign());

        Date statusDtUnloading = DateUtils.stringToDateTime(importShippingNoteDTO.getStatusDtUnloading());

        Date statusDtLoading = DateUtils.stringToDateTime(importShippingNoteDTO.getStatusDtLoading());

        Date statusDtReceive = DateUtils.stringToDateTime(importShippingNoteDTO.getStatusDtReceive());

        //如果运单导入里填了上报完成，要设置上报完成状态
        if (StrUtil.isNotEmpty(importShippingNoteDTO.getUploadStatus()) && importShippingNoteDTO.getUploadStatus().equals("上报成功")) {
            hyShippingNote.setUploadStatus("1");
        }
        //如果导入时填了老系统的原始运单号，保留该运单号
        if (StrUtil.isNotEmpty(importShippingNoteDTO.getOrgShippingNumber())) {
            hyShippingNote.setShippingNoteNumber(importShippingNoteDTO.getOrgShippingNumber());
        } else {
            hyShippingNote.setShippingNoteNumber(codeUtil.createShippingNum(createTime));
        }

        //如果导入时填了合同编号和照片
        String date = DateUtils.dateToStringNoBar(new Date());
        String serverFolderPath = this.uploadpath + File.separator + "documents" ;
        if (StrUtil.isNotEmpty(importShippingNoteDTO.getShippingContract())) {

            //合同照片地址
            //String shippingContract = PhotoCrawlerUtil.downloadAbsolutePathPic(importShippingNoteDTO.getShippingContract(), serverFolderPath, date);
            this.applicationEventPublisher.publishEvent(PicDownloadEvent.builder()
                    .type("contract")
                    .downloadUrl(importShippingNoteDTO.getShippingContract())
                    .serverFolderPath(serverFolderPath)
                    .serverFolderName(date)
                    .build()
            );

            //覆盖导入的长地址，启用网货平台对应的短地址,前面拼接documents目录
            int lastIndex = importShippingNoteDTO.getShippingContract().lastIndexOf('/');
            String filename = importShippingNoteDTO.getShippingContract().substring(lastIndex);
            String filenameNoSubfix = filename.substring(0, filename.lastIndexOf("."));
            hyShippingNote.setShippingContract("documents/" + date + "/" + filenameNoSubfix + ".pdf");
            log.info("保存合同地址, {} {} {}", hyShippingNote.getShippingNoteNumber(), importShippingNoteDTO.getContractNum(), importShippingNoteDTO.getShippingContract());

            if (StrUtil.isNotEmpty(importShippingNoteDTO.getContractNum())) {
                hyShippingNote.setContractNum(importShippingNoteDTO.getContractNum());
                hyShippingNote.setContractNum2(importShippingNoteDTO.getContractNum());
                hyShippingNote.setContractType("承运人电子合同");
                hyShippingNote.setContractStatus("1");
                hyShippingNote.setContractOr("0");
            }
        }
        //Added start at 2025-02-11 for 导入装卸货磅单
        if (StrUtil.isNotEmpty(importShippingNoteDTO.getImgLoading())) {
            this.applicationEventPublisher.publishEvent(PicDownloadEvent.builder()
                    .type("loading")
                    .downloadUrl(importShippingNoteDTO.getImgLoading())
                    .serverFolderPath(serverFolderPath)
                    .serverFolderName(date)
                    .build()
            );
            int lastIndex = importShippingNoteDTO.getImgLoading().lastIndexOf('/');
            String filename = importShippingNoteDTO.getImgLoading().substring(lastIndex);
            hyShippingNote.setImgLoading("documents/" + date + "/" + filename);
            Thread.sleep(300);
        }

        if (StrUtil.isNotEmpty(importShippingNoteDTO.getImgUnloading())) {
            this.applicationEventPublisher.publishEvent(PicDownloadEvent.builder()
                    .type("unloading")
                    .downloadUrl(importShippingNoteDTO.getImgUnloading())
                    .serverFolderPath(serverFolderPath)
                    .serverFolderName(date)
                    .build()
            );
            int lastIndex = importShippingNoteDTO.getImgUnloading().lastIndexOf('/');
            String filename = importShippingNoteDTO.getImgUnloading().substring(lastIndex);
            hyShippingNote.setImgUnloading("documents/" + date + "/" + filename);
        }
        //Added end at 2025-02-11 for 导入装卸货磅单

        //如果导入了油气费用
        if (StrUtil.isNotEmpty(importShippingNoteDTO.getGasRechargeAmount())) {
            hyShippingNote.setGasRechargeAmount(new BigDecimal(importShippingNoteDTO.getGasRechargeAmount()));
            hyShippingNote.setIzUsedGas(importShippingNoteDTO.getIzUsedGas());
        }

        hyShippingNote.setCompanyId(importShippingNoteDTO.getCompanyId());
        hyShippingNote.setDriverId(importShippingNoteDTO.getDriverId());
        hyShippingNote.setCustomerId(importShippingNoteDTO.getCustomerId());
        hyShippingNote.setOrderId(importShippingNoteDTO.getOrderId());

        //如果导入的是车队长模式，不设置司机个人银行卡信息
        if (!hyOrder.getPayType().equals("2")) {
            hyShippingNote.setDriverBankId(importShippingNoteDTO.getDriverBankId());
        }
        hyShippingNote.setVehicleId(importShippingNoteDTO.getVehicleId());

        BigDecimal goodsWeightLoading = null;
        BigDecimal costPay = null;
        BigDecimal costPay1 = null;
        BigDecimal costPay2 = null;
        BigDecimal costPay3 = null;
        //支付计划
        String izUsedPayPlan = importShippingNoteDTO.getIzUsedPayPlan();
        if("1".equals(izUsedPayPlan)){
            HyStatusCheckUtil.checkPlanFee_PayType(hyOrder.getPayType());
            HyStatusCheckUtil.checkPlanFee_OrderMode(hyOrder.getOrderMode());//检查订单模式

            goodsWeightLoading = importShippingNoteDTO.getGoodsWeightLoading();

            if("4".equals(hyOrder.getShippingType())){
                costPay = importShippingNoteDTO.getShippingUnitPrice() ;
            }else {
                costPay = goodsWeightLoading.multiply(importShippingNoteDTO.getShippingUnitPrice());
            }

            HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(hyOrder.getCustomerId());
            if (customerCompany == null) {
                throw new JeecgBootException("第" + key + "行未找到货主签约信息");
            }
            costPay1 = importShippingNoteDTO.getCostPay1();//首付
            if(costPay1.compareTo(BigDecimal.ZERO) < 0){
                throw new JeecgBootException("第" + key + "行首付运费错误");
            }
            costPay2 = importShippingNoteDTO.getCostPay2();//到付
            if(costPay2.compareTo(BigDecimal.ZERO) < 0){
                throw new JeecgBootException("第" + key + "行到付运费错误");
            }
            costPay3 = importShippingNoteDTO.getCostPay3();//尾款
            if(costPay3.compareTo(BigDecimal.ZERO) <= 0){
                throw new JeecgBootException("第" + key + "行尾款运费错误");
            }
            BigDecimal cost = costPay1.add(costPay2).add(costPay3);
            if(costPay.compareTo(cost) != 0){
                throw new JeecgBootException("第" + key + "行运费计算错误");
            }

            hyShippingNote.setGoodsWeightLoading(goodsWeightLoading);
            hyShippingNote.setGoodsWeightUnloading(goodsWeightLoading);//装卸货量相同
            hyShippingNote.setIzUsedPayPlan("1");
            hyShippingNote.setCostPay(costPay);//司机运费
            hyShippingNote.setCostPay1(costPay1);//首付
            hyShippingNote.setCostPay2(costPay2);//到付
            hyShippingNote.setCostPayShipping(costPay3);//尾款
            //计算货主服务费等其他项
            HyCalcFeeUtil.calcPayPlan(hyShippingNote,customerCompany);
        }else {
            hyShippingNote.setGoodsWeightLoading(importShippingNoteDTO.getGoodsWeightLoading());
            hyShippingNote.setGoodsWeightUnloading(importShippingNoteDTO.getGoodsWeightUnloading());
            hyShippingNote.setCostPay(importShippingNoteDTO.getCostPay());
            hyShippingNote.setCostPayShipping(importShippingNoteDTO.getCostPayShipping());
            hyShippingNote.setCostPayTotal(importShippingNoteDTO.getCostPay());
            hyShippingNote.setIzUsedPayPlan("0");
            hyShippingNote.setCostService(BigDecimal.ZERO);
        }

        hyShippingNote.setShippingUnitPrice(importShippingNoteDTO.getShippingUnitPrice());

        hyShippingNote.setShippingStatus(importShippingNoteDTO.getShippingStatus());
        hyShippingNote.setCreateTime(createTime);
        hyShippingNote.setStatusDtReceive(statusDtReceive);
        hyShippingNote.setStatusDtLoading(statusDtLoading);
        hyShippingNote.setStatusDtUnloading(statusDtUnloading);
        hyShippingNote.setStatusDtSign(statusDtSign);
        hyShippingNote.setShippingPayStatus(importShippingNoteDTO.getShippingPayStatus());

        hyShippingNote.setSendAddress(
                StringUtils.isNotBlank(importShippingNoteDTO.getSendAddress()) ? importShippingNoteDTO.getSendAddress() : hyOrder.getSendAddress()
        );

        hyShippingNote.setReceiveAddress(
                StringUtils.isNotBlank(importShippingNoteDTO.getReceiveAddress()) ? importShippingNoteDTO.getReceiveAddress() : hyOrder.getReceiveAddress()

        );

        //  hyShippingNote.setTransportationDistance(importShippingNoteDTO.getTransportationDistance());

//        hyShippingNote.setLossGoodsUnitPrice(BigDecimal.ZERO);
        hyShippingNote.setGoodsWeightLoss(hyShippingNote.getGoodsWeightLoading().subtract(hyShippingNote.getGoodsWeightUnloading()));
        hyShippingNote.setCostLoss(BigDecimal.ZERO);
//        hyShippingNote.setLossProportion(BigDecimal.ZERO);
//        hyShippingNote.setShippingType("1");
//        hyShippingNote.setOrderMode("1");
//        if("5".equals(importShippingNoteDTO.getShippingPayStatus())){
//            hyShippingNote.setPayChannel( "1" );
//        }

        hyShippingNote.setImportFlag("1");
        return hyShippingNote;
    }


    /**
     * 装卸货凭证添加水印
     *
     * @param shippingNote
     * @param urlFile
     * @param type         凭证类型 send/receive
     * @return
     */
    @Override
    public String buildWaterMarkImg(HyShippingNote shippingNote, String urlFile, String type) {

        if (shippingNote == null || StringUtils.isEmpty(urlFile)) {
            return StringUtils.EMPTY;
        }

        HyVehicle vehicle = vehicleService.getById(shippingNote.getVehicleId());
        if (vehicle == null) {
            return StringUtils.EMPTY;
        }

        //        HyOrder order = orderService.getById(shippingNote.getOrderId());
        //        if (order == null) {
        //            return StringUtils.EMPTY;
        //        }

        String bizPath = "wlhy/"  + DateUtils.getDate("yyyyMMdd");
        Date dateTime = type.equals("send") ? shippingNote.getStatusDtLoading() : shippingNote.getStatusDtUnloading();
        String address = type.equals("send") ? shippingNote.getSendAddress() : shippingNote.getReceiveAddress();
        Date dateTimes = dateTime == null ? new Date() : dateTime;
        //.append(vehicle.getVehicleNumber() +"||")
        //.append(order.getDescriptionOfGoods() +"||")
        String waterMarkContent = new StringBuilder().append(DateUtils.dateTimeToString(dateTimes) + "||")
                .append(address).toString();

        //除了昆交，其他得水印颜色改为红色
        String urlImg = null;
        log.info("serverName=="+serviceName);
        if (serviceName.equals("https://www.e-zhijian.com")){
            log.info("进入昆交模式");
            urlImg = NewWaterMarkUtils.waterPress(uploadpath + "/" + urlFile, uploadpath + "/" + bizPath, Color.BLACK, 30, waterMarkContent);
        }else {
            urlImg = NewWaterMarkUtils.waterPress(uploadpath + "/" + urlFile, uploadpath + "/" + bizPath, Color.RED, 30, waterMarkContent);
        }
        return StringUtils.isNotEmpty(urlImg) ? urlImg.replace(uploadpath + "/", "") : StringUtils.EMPTY;
    }


    @Override
    public List<HyShippingNoteDTO> getList(QueryWrapper<HyShippingNoteDTO> queryWrapper) {
        return baseMapper.getList(queryWrapper);
    }

    @Override
    public HyShippingNote addByOrder(HyOrder order, HyDriver driver , String companyId){
        String orderId = order.getId();
        HyShippingNote hyShippingNote = new HyShippingNote();

        hyShippingNote.setIzDbOrder(order.getIzDbOrder());
        hyShippingNote.setOrderCode(order.getOrderCode());

    	if("4".equals(order.getOrderMode())){
            hyShippingNote.setCustomerShippingType(order.getCustomerShippingType());
            hyShippingNote.setCustomerUnitPrice(order.getCustomerPrice());
        }

     	hyShippingNote.setRemark(order.getRemark());
        //智运宝派单时可以先不传司机，通过收货后进行信息补全
        if (ObjectUtil.isNotEmpty(driver)) {
            hyShippingNote.setDriverId(driver.getId());
        }
        //hyShippingNote.setDriverId(driver.getId());
        hyShippingNote.setOrderId(orderId);//货源id
        hyShippingNote.setKhdh(order.getKhdh());
        hyShippingNote.setDispatcher(order.getDispatcher());
        hyShippingNote.setIntroducer(order.getIntroducer());
        hyShippingNote.setCustomerId(order.getCustomerId());//货主id
        hyShippingNote.setCompanyId(companyId);//设置公司id

        hyShippingNote.setStatusDtReceive(new Date());//接单时间

        //设置运单 运费单价，亏损单价，亏损比例
        //运费单价
        hyShippingNote.setShippingUnitPrice(order.getShippingUnitPrice());
        hyShippingNote.setShippingType(order.getShippingType());
        //亏损货物单价
        hyShippingNote.setLossGoodsUnitPrice(order.getLossGoodsUnitPrice());
        //亏损方式(1吨数2比例)
        hyShippingNote.setLossType(order.getLossType());
        //亏损免赔比例
        hyShippingNote.setLossProportion(order.getLossProportion());

        //结算方式 1 司机个人 2 车队长结算
        hyShippingNote.setPayType(order.getPayType());
        //车队长id
        hyShippingNote.setCarrierId(order.getCarrierId());

        hyShippingNote.setOrderMode(order.getOrderMode());
        if ("3".equals(order.getOrderMode())) {
            hyShippingNote.setAgentId(order.getAgentId()); //设置经纪人
            hyShippingNote.setAgentPrice(order.getAgentPrice());//经纪人运费
        }

        //收发货地址 2021-10-12
        hyShippingNote.setAddressSendId(order.getAddressSendId());
        hyShippingNote.setSendDate(order.getSendDate());
        hyShippingNote.setSendAddressName(order.getSendAddressName());
        hyShippingNote.setSendLongitude(order.getSendLongitude());
        hyShippingNote.setSendLatitude(order.getSendLatitude());
        hyShippingNote.setSendAddress(order.getSendAddress());
        hyShippingNote.setSendAreaCode(order.getSendAreaCode());
        hyShippingNote.setSendContactName(order.getSendContactName());
        hyShippingNote.setSendContactTel(order.getSendContactTel());

        //收发货地址 2021-10-12
        hyShippingNote.setAddressReceiveId(order.getAddressReceiveId());
        hyShippingNote.setReceiveDate(order.getReceiveDate());
        hyShippingNote.setReceiveAddressName(order.getReceiveAddressName());
        hyShippingNote.setReceiveLongitude(order.getReceiveLongitude());
        hyShippingNote.setReceiveLatitude(order.getReceiveLatitude());
        hyShippingNote.setReceiveAddress(order.getReceiveAddress());
        hyShippingNote.setReceiveAreaCode(order.getReceiveAreaCode());
        hyShippingNote.setReceiveContactName(order.getReceiveContactName());
        hyShippingNote.setReceiveContactTel(order.getReceiveContactTel());

        //2021-10-13添加
        hyShippingNote.setBusinessTypeCode(order.getBusinessTypeCode());
        hyShippingNote.setGoodsUnit(order.getGoodsUnit());
        hyShippingNote.setDescriptionOfGoods(order.getDescriptionOfGoods());
        hyShippingNote.setCargoTypeClassificationCode(order.getCargoTypeClassificationCode());
        hyShippingNote.setCube(order.getCube());
        hyShippingNote.setUnloadingFee(order.getUnloadingFee());
        hyShippingNote.setInformationFee(order.getInformationFee());
        hyShippingNote.setServiceFee(order.getServiceFee());
        hyShippingNote.setBz(order.getBz());
        hyShippingNote.setUnloadingBz(order.getUnloadingBz());

        //预付运费
        hyShippingNote.setPreUnitFee(order.getPreUnitFee());
        hyShippingNote.setPreType(order.getPreType());

        //车队长运费
        String carrierFeeType = order.getCarrierFeeType();
        hyShippingNote.setCarrierFeeType(carrierFeeType);
        if("1".equals(carrierFeeType) || "2".equals(carrierFeeType)){
            if(order.getCarrierUnitFee() == null){
                throw new JeecgBootException("货源车队长运费单价错误");
            }
            hyShippingNote.setCarrierUnitFee(order.getCarrierUnitFee());
        }else {
            hyShippingNote.setCarrierFeeType("0");
            hyShippingNote.setCarrierUnitFee(BigDecimal.ZERO);
        }

        String num = codeUtil.createShippingNum();
        hyShippingNote.setShippingNoteNumber(num);

        //货源参数2023-03-29
        if("1".equals(order.getIzOrderSet())) {
            hyShippingNote.setIzDriverPayset(order.getIzDriverPayset());
            hyShippingNote.setIzDriverMl(order.getIzDriverMl());
            hyShippingNote.setDriverMlWs(order.getDriverMlWs());
            hyShippingNote.setDriverMlFw(order.getDriverMlFw());
            hyShippingNote.setIzZd(order.getIzZd());
            hyShippingNote.setZdJs(order.getZdJs());
        }else {
            HyCustomerConfig customerConfig = hyCustomerConfigService.getByCustomerId(order.getCustomerId());
            if (customerConfig == null) {
                throw new JeecgBootException("未找到货主参数配置");
            }
            hyShippingNote.setIzDriverPayset(customerConfig.getIzDriverPayset());
            hyShippingNote.setIzDriverMl(customerConfig.getIzDriverMl());
            hyShippingNote.setDriverMlWs(customerConfig.getDriverMlWs());
//            hyShippingNote.setDriverMlFw(customerConfig.getDriverMlFw());
            hyShippingNote.setIzZd(customerConfig.getIzZd());
            BigDecimal zdJs = customerConfig.getZdJs();
            if(zdJs != null) {
                hyShippingNote.setZdJs(zdJs.toPlainString());
            }
        }

        return hyShippingNote;
    }

    @Override
    @Transactional
    public Result<?> addByOrder(HyOrder order, HyDriver driver, HyVehicle vehicle, HyOrderPrice orderPrice, String shippingContract, String shippingContract2, String driverBankId) {

//        HyConfig config = HyConfigUtils.getConfig();
//        if(config.getPfIzUse()){
//            //检查司机是否开通钱包
//            HyPfAccount driverAccount = hyPfAccountService.getDriverAccount(driver.getId());
//            if(driverAccount == null){
//                return Result.error("司机未开通钱包，不能接单");
//            }
//        }



        String driver_is_examine = hySettingService.getSettingValueByTag2("driver_is_examine");

        //0关闭 1打开
        if(StringUtils.isNotEmpty(driver_is_examine)){

            if("1".equals(driver_is_examine)){

                Result<?> result = hyDriverService.checkVehicleOverdueTime(driver, vehicle);
                if(result.getCode().equals(500)){
                    return Result.error(result.getMessage());
                }

                if("3".equals(driver.getExamineStatus())){
                    String examinRemark = driver.getExaminRemark();
                    if(StringUtils.isNotBlank(examinRemark)){
                        return Result.error(-3,examinRemark + ",不能接单，请及时更正");
                    }
                    return Result.error(-3,"因证件信息错误，暂不能接单，请及时更正");
                }

                if("3".equals(vehicle.getExamineStatus())){
                    String examinRemark = vehicle.getExaminRemark();
                    if(StringUtils.isNotBlank(examinRemark)){
                        return Result.error(-4,examinRemark + ",不能接单，请及时更正");
                    }
                    return Result.error(-4,"因证件信息错误，暂不能接单，请及时更正");
                }

            }
        }

        HyDriver td = hyDriverService.getbyIdForUpdate(driver.getId());//不能删除
//      HyShippingNote currentShippingNote =   hyDriverService.getCurrentShippingNote(driver.getDriverId());

        boolean driverMultipleOrders = HyCfgUtil.isUsed2("driver_multiple_orders");
        if (driverMultipleOrders) {
            //如果当前司机有在途运单的话，需要进入额外条件判断
            int total = hyDriverService.getCurrentShippingNoteCount(driver.getId());
            if (total >= 1 ) {

                if (0 < hyDriverService.getCurrentShippingNoteCount(driver.getId(), order.getId())) {
                    return Result.error("当前货源有没完成的运单,不能再接单");
                }

                //限制不同货源同时接单，最多可以接几单
                if (HyCfgUtil.getCfgItem2("driver_multiple_orders","limit_number") != null) {
                    Integer number = Integer.valueOf(HyCfgUtil.getCfgItem2("driver_multiple_orders","limit_number"));
                    if (total >= number) {
                        return Result.error("当前已接" + total + "单,不能再接单了");
                    }
                }

//                //限制不同货源的收货地必须在同一个市的区域内（只精确到市）
//                if (HyCfgUtil.getCfgItem2("driver_multiple_orders","same_city") != null) {
//                    List<HyShippingNote> hyShippingNoteList = this.hyDriverService.getCurrentShippingNote(driver.getId());
//                    if (CollUtil.isNotEmpty(hyShippingNoteList)) {
//                        //取一个运单的城市编码进行对比
//                        HyShippingNote hyShippingNote = hyShippingNoteList.get(0);
//
//                    }
//                    //String areaCode = order.getReceiveAreaCode();
//                    //this.getCurrentShippingNote();
//                    //this.hyAreaService.getOne()
//                }
            }
        } else {
            int shippingNoteTotal = hyDriverService.getCurrentShippingNoteCount(driver.getId());
            if (shippingNoteTotal >= 1 ) {
                return Result.error("当前有没完成的运单,不能再接单");
            }
        }

//        HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(order.getCustomerId());

        if(StringUtils.isEmpty(order.getCostServiceId())){
            return Result.error("未找到货源货主签约信息");
        }
        HyCustomerCompany customerCompany = hyCustomerCompanyService.getById(order.getCostServiceId());


        if (customerCompany == null) {
            return Result.error("未找到货主签约信息");
        }

        if (order.getOrderSetting()) {
            if(order.getTotalGoodsWeight()!=null){
                //已经拉的重量
                BigDecimal finishWeight = hyOrderService.getShippingFinishWeightById(order.getId());
                //总重量-已完成=剩余
                BigDecimal subtract = order.getTotalGoodsWeight().subtract(finishWeight);
                if (subtract.compareTo(vehicle.getVehicleTonnage()) == -1 ) {
                    return Result.error("货源货量不足");
                }
            }else{
                return Result.error("货源货量不能为空");
            }

        }
        String orderId = order.getId();
        String vehicleId = vehicle.getId();
        HyShippingNote hyShippingNote = this.addByOrder(order , driver , customerCompany.getCompanyId());
        hyShippingNote.setVehicleId(vehicleId);
        hyShippingNote.setShippingStatus(ShippingStatus.已接单.getValue());//设置为已接单状态
        hyShippingNote.setDriverBankId(driverBankId);

        //1.辽宁航信税务平台 创建运单条件1：司机和车辆同时上传成功
        if (HyCfgUtil.isUsed2("liaoning_tax_report")) {
            HyCompany hyCompany = this.companyService.getById(customerCompany.getCompanyId());
            HyCompanyConfig hyCompanyConfig = this.companyConfigService.getByCompanyId(customerCompany.getCompanyId());
            log.info("校验辽宁税务司机、车辆，{} - {} - {} - {} - {}", hyCompany.getCompanyName(), hyCompanyConfig.getTaxUploadType(), hyShippingNote.getShippingNoteNumber(), driver.getLnTaxUploadStatus(), vehicle.getLnTaxUploadStatus());
            if (3 == hyCompanyConfig.getTaxUploadType().intValue()) {
                if (StringUtils.isNotEmpty(driver.getLnTaxUploadStatus()) && StringUtils.isNotEmpty(vehicle.getLnTaxUploadStatus())) {

                    boolean bDriver = driver.getLnTaxUploadStatus().startsWith("1");
                    boolean bVehicle = vehicle.getLnTaxUploadStatus().startsWith("1");
                    if (bDriver && bVehicle) {
                        hyShippingNote.setAlctIdentification("1");
                    } else {
                        return Result.error("司机或车辆税务状态错误,请先上报数据");
                    }

//                List<String> driverSt = Arrays.asList(driver.getLnTaxUploadStatus().split("\\|")).stream().distinct().collect(
//                        Collectors.toList());
//                List<String> vehicleSt = Arrays.asList(vehicle.getLnTaxUploadStatus().split("\\|")).stream().distinct().collect(
//                        Collectors.toList());
//
//                //如果司机和车辆的辽宁税务状态上报正常，将运单设置为允许进行辽宁税务业务状态
//                if (driverSt.size() == 1 && vehicleSt.size() == 1) {
//                    hyShippingNote.setAlctIdentification("1");
//                } else {
//                    return Result.error("司机或车辆税务状态错误,请先上报数据");
//                }
                } else {
                    return Result.error("司机或车辆数据未上报税务系统");
                }

                String authFlag = HyCfgUtil.getCfgItem2("liaoning_tax_report", "realname_auth");
                if ("1".equals(authFlag)) {
                    //2.辽宁航信税务平台 创建运单条件2: 如果开启实名认证
                    Result rDriverAuth = this.shippingNoteApiAlct56Service.queryDriverForAuth(driver);
                    //如果返回-3，会返回微信认证链接，需要司机去认证
                    if (-3 == rDriverAuth.getCode()) {
                        return Result.error(-3, driver.getDriverName() + "司机未实名认证，请先通过司机App进行实名认证");
                    }
                }
            }
        }

        if (HyCfgUtil.isUsed2("ordos_report")) {
            HyCompany hyCompany = this.companyService.getById(customerCompany.getCompanyId());
            HyCompanyConfig hyCompanyConfig = this.companyConfigService.getByCompanyId(customerCompany.getCompanyId());
            log.info("校验鄂尔多斯市上报司机、车辆，{} - {} - {} - {} - {}", hyCompany.getCompanyName(), hyCompanyConfig.getParkReportPlatformType(), hyShippingNote.getShippingNoteNumber(), driver.getZjUploadStatus(), vehicle.getZjUploadStatus());
            if (hyCompanyConfig.getParkReportPlatformType().intValue() == 200) {
                if (!"1".equals(driver.getZjUploadStatus())) {
                    return Result.error("司机数据未上报鄂尔多斯市监管平台");
                }

                if (!"1".equals(vehicle.getZjUploadStatus())) {
                    return Result.error("车辆数据未上报鄂尔多斯市监管平台");
                }
            }
        }

        //油气
        String izUsedGas = order.getIzUsedGas();
        if ("0".equals(izUsedGas)) {
            hyShippingNote.setIzUsedGas("0");
            hyShippingNote.setGasRechargeAmount(BigDecimal.ZERO);
        } else {
            //检查油气金额
            BigDecimal gasRechargeAmount = order.getGasRechargeAmount();
            if (gasRechargeAmount == null) {
                return Result.error("分配油气金额不正确");
            }
            // <=
            if (gasRechargeAmount.compareTo(BigDecimal.ZERO) == -1) {
                return Result.error("分配油气金额不正确");
            }
//            if ("1".equals(izUsedGas)) {
//                //万金油
//            }
//            if ("2".equals(izUsedGas)) {
//                //油气卡
//            }
//            if ("3".equals(izUsedGas)) {
//                //油气平台
//            }
            hyShippingNote.setIzUsedGas(izUsedGas);//使用油气
            hyShippingNote.setGasRechargeAmount(gasRechargeAmount);
        }
        //运输合同地址
        if (StringUtils.isNotEmpty(shippingContract)) {
            //查询使用合同模板是哪个
            String contractTemplate = "0";
            String contract_template = hySettingService.getSettingValueByTag2("contract_template");
            if (!StringUtils.isEmpty(contract_template)) {
                contractTemplate = contract_template;
            }
            if (contractTemplate.equals("0")) {
                //设置运输协议地址
                hyShippingNote.setShippingContract(shippingContract);
                String contractNum = CodeUtil.createContractNum();
                hyShippingNote.setContractNum(contractNum);
                hyShippingNote.setContractNum2(contractNum);
                hyShippingNote.setContractType("承运人电子合同");
                hyShippingNote.setContractStatus("1");
                hyShippingNote.setContractOr("0");
            }
        }

        //税务授权协议
        if (StringUtils.isNotEmpty(shippingContract2)) {
            //税务授权协议
            hyShippingNote.setShippingContract2(shippingContract2);
            driver.setSwAgreement(shippingContract2);
            hyDriverService.updateById(driver);
        }

        //运输里程，只是经纬度计算直线距离，如果想准确需要调用模拟轨迹接口
//        double m = LngLonUtil.GetDistance(order.getSendLatitude(), order.getSendLongitude(),
//                order.getReceiveLatitude(), order.getReceiveLongitude());
//        double km = Math.round((m / 100d) / 10d);
//        hyShippingNote.setTransportationDistance(String.valueOf((int) Math.round(km)));

        if (orderPrice != null) {
            //设置竞价价格
            hyShippingNote.setShippingUnitPrice(orderPrice.getPrice());
        }

        //快货运平台 创建运单条件：司机和车辆同时上传成功
        if (StringUtils.isNotEmpty(driver.getTosUploadDriverStatus()) && "1".equals(driver.getTosUploadDriverStatus()) &&
                StringUtils.isNotEmpty(vehicle.getTosUploadStatus()) && "1".equals(vehicle.getTosUploadStatus())) {
            hyShippingNote.setTosIdentification("1");
        }

        //辽宁税务上报，必须税务平台返回创建成功后才能创建运单
        if ("1".equals(hyShippingNote.getAlctIdentification())) {
            Result result = this.shippingNoteApiAlct56Service.createShippingNote(hyShippingNote);
            if (!result.getCode().equals(CommonConstant.SC_OK_200)) {
                return Result.error("税务系统返回错误: " + result.getMessage());
            }
        }

        List<HyOrderSendAddress> sendList = hyOrderSendAddressService.getListByOrderId(orderId);
        List<HyOrderReceiveAddress> receiveList = hyOrderReceiveAddressService.getListByOrderId(orderId);
        List<HyShippingNoteSendAddress> shippingNoteSendAddresses = new ArrayList<>();
        List<HyShippingNoteReceiveAddress> shippingNoteReceiveAddresses = new ArrayList<>();

        for (HyOrderSendAddress hyOrderSendAddress : sendList) {
            HyShippingNoteSendAddress shippingNoteSendAddress = new HyShippingNoteSendAddress();
            BeanUtils.copyProperties(hyOrderSendAddress, shippingNoteSendAddress);
            shippingNoteSendAddresses.add(shippingNoteSendAddress);
        }

        for (HyOrderReceiveAddress receiveAddress : receiveList) {
            HyShippingNoteReceiveAddress shippingNoteReceiveAddress = new HyShippingNoteReceiveAddress();
            BeanUtils.copyProperties(receiveAddress, shippingNoteReceiveAddress);
            shippingNoteReceiveAddresses.add(shippingNoteReceiveAddress);
        }
       /* //如果为一键补单的话则设置为2
        if (order.getOrderImportFlag().equals("2")){
            hyShippingNote.setImportFlag("2");
        }*/
        this.save(hyShippingNote);

        if (sendList != null) {
            for (HyShippingNoteSendAddress shippingNoteSendAddress : shippingNoteSendAddresses) {
                shippingNoteSendAddress.setId(null);
                shippingNoteSendAddress.setShippingId(hyShippingNote.getId());
            }
            hyShippingNoteSendAddressService.saveBatch(shippingNoteSendAddresses);
        }
        if (receiveList != null) {
            for (HyShippingNoteReceiveAddress shippingNoteReceiveAddress : shippingNoteReceiveAddresses) {
                shippingNoteReceiveAddress.setId(null);
                shippingNoteReceiveAddress.setShippingId(hyShippingNote.getId());
            }
            hyShippingNoteReceiveAddressService.saveBatch(shippingNoteReceiveAddresses);
        }

        if (orderPrice != null) {
            orderPrice.setPriceSt("2");//接单
            orderPrice.setShippingId(hyShippingNote.getId());
            orderPrice.setVehicleId(hyShippingNote.getVehicleId());
            orderPrice.setJdTime(new Date());
            hyOrderPriceService.updateById(orderPrice);
        }

        //运单创建-订阅消息
        if ("1".equals(hyShippingNote.getTosIdentification())) {
            GenMqUtil.sendMsg(EnumGenHandler.SHIPPING_CREATE, "TosApi", hyShippingNote);
        }
        //如果是德邦运单
        if("1".equals(hyShippingNote.getIzDbOrder())){
            //发送德邦推送车辆信息事件
            this.applicationEventPublisher.publishEvent(DeBangEvent.builder()
                    .uploadType("CHE")
                    .shippingId(hyShippingNote)
                    .build());
//            GenMqUtil.sendMsg(EnumGenHandler.DE_BANG, "CHE", hyShippingNote);
        }

        return Result.OK(hyShippingNote);
    }


    /**
     * 运单装卸货榜单图片添加水印
     *
     * @param hyShippingNote
     * @param imgLoading
     * @param imgUnloading
     * @param oldimgLoading
     * @param oldImgUnloading
     */
    @Override
    public void getWatermarkPic(HyShippingNote hyShippingNote,
                                String imgLoading, String imgUnloading,
                                String oldimgLoading, String oldImgUnloading) {

        //装卸货榜单加水印
        if (StringUtils.isNotEmpty(imgLoading)) {

            List<String> imgLoadings = Arrays.asList(imgLoading.split(","));
            Map<String, String> imgLoadingMap = new HashMap<>();
            if (StringUtils.isNotEmpty(oldimgLoading)) {
                for (String img : imgLoadings) {
                    imgLoadingMap.put(img, img);
                }
                //装卸货榜单加水印
                List<String> imgLoadingsAll = Arrays.asList(oldimgLoading.split(","));
                List<String> newImgLoadings = imgLoadings.stream().filter(item -> !imgLoadingsAll.contains(item))
                        .collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(newImgLoadings)) {
                    for (String newImgLoading : newImgLoadings) {
                        String newWaterMarkImgLoading = this.buildWaterMarkImg(hyShippingNote, newImgLoading, "send");
                        String waterMarkImgLoading = StringUtils
                                .isNotEmpty(newWaterMarkImgLoading) ? newWaterMarkImgLoading : newImgLoading;
                        if (imgLoadingMap.get(newImgLoading) != null) {
                            imgLoadingMap.put(newImgLoading, waterMarkImgLoading);
                        }
                    }
                }
            } else {
                for (String newImgLoading : imgLoadings) {
                    String newWaterMarkImgLoading = this.buildWaterMarkImg(hyShippingNote, newImgLoading, "send");
                    String waterMarkImgLoading = StringUtils
                            .isNotEmpty(newWaterMarkImgLoading) ? newWaterMarkImgLoading : newImgLoading;
                    imgLoadingMap.put(newImgLoading, waterMarkImgLoading);
                }
            }
            List<String> imgLoadingMaplist = imgLoadingMap.values().stream().collect(Collectors.toList());
            hyShippingNote.setImgLoading(StringUtils.join(imgLoadingMaplist, ","));
        }

        if (StringUtils.isNotEmpty(imgUnloading)) {
            List<String> imgUnLoadings = Arrays.asList(imgUnloading.split(","));
            Map<String, String> imgUnLoadingMap = new HashMap<>();
            if (StringUtils.isNotEmpty(oldImgUnloading)) {
                List<String> imgUnLoadingsAll = Arrays.asList(oldImgUnloading.split(","));
                for (String unimg : imgUnLoadings) {
                    imgUnLoadingMap.put(unimg, unimg);
                }
                List<String> newImgUnLoadings = imgUnLoadings.stream().filter(item -> !imgUnLoadingsAll.contains(item))
                        .collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(newImgUnLoadings)) {
                    for (String newImgUnLoading : newImgUnLoadings) {
                        String newWaterMarkImgUnLoading = this.buildWaterMarkImg(hyShippingNote, newImgUnLoading, "receive");
                        String waterMarkImgUnLoading = StringUtils
                                .isNotEmpty(newWaterMarkImgUnLoading) ? newWaterMarkImgUnLoading : newImgUnLoading;
                        if (imgUnLoadingMap.get(newImgUnLoading) != null) {
                            imgUnLoadingMap.put(newImgUnLoading, waterMarkImgUnLoading);
                        }
                    }
                }
            } else {
                for (String newImgUnLoading : imgUnLoadings) {
                    String newWaterMarkImgUnLoading = this.buildWaterMarkImg(hyShippingNote, newImgUnLoading, "receive");
                    String waterMarkImgUnLoading = StringUtils
                            .isNotEmpty(newWaterMarkImgUnLoading) ? newWaterMarkImgUnLoading : newImgUnLoading;
                    imgUnLoadingMap.put(newImgUnLoading, waterMarkImgUnLoading);
                }
            }

            List<String> imgUnLoadingMaplist = imgUnLoadingMap.values().stream().collect(Collectors.toList());
            hyShippingNote.setImgUnloading(StringUtils.join(imgUnLoadingMaplist, ","));
        }
    }

//    /**
//     * 临时更新数据用
//     */
//    @Override
//    public void upWaterMarkImg1() {
//        SimpleDateFormat now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Long start = System.currentTimeMillis();
//        LOGGER.info(" upWaterMarkImg:" + now.format(new Date()));
//        QueryWrapper<HyShippingNote> queryWrapper = new QueryWrapper();
//        queryWrapper.eq("shipping_pay_status", "6");
//        List<HyShippingNote> shippingNotes = this.list(queryWrapper);
//        LOGGER.info(" shippingNotes : {}", shippingNotes);
//
//        if (CollectionUtils.isNotEmpty(shippingNotes)) {
//            for (HyShippingNote hyShippingNote : shippingNotes) {
//                String waterMarkImgLoading = this.buildWaterMarkImg(hyShippingNote, hyShippingNote.getImgLoading(), "send");
//                hyShippingNote.setImgLoading(
//                        StringUtils.isNotEmpty(waterMarkImgLoading) ? waterMarkImgLoading : hyShippingNote.getImgLoading()
//                );
//                String waterMarkImgUnloading = this.buildWaterMarkImg(hyShippingNote, hyShippingNote.getImgUnloading(), "receive");
//                hyShippingNote.setImgUnloading(
//                        StringUtils.isNotEmpty(waterMarkImgUnloading) ? waterMarkImgUnloading : hyShippingNote.getImgUnloading()
//                );
//                this.updateById(hyShippingNote);
//            }
//        }
//        LOGGER.info(" upWaterMarkImg,耗时:" + (System.currentTimeMillis() - start) + "毫秒----");
//    }

    @Override
    public HyShippingNote getByIdForUpdate(String id) {
        return baseMapper.selectByIdForUpdate(id);
    }

    @Override
    public List<HyShippingNote> listByIdsForUpdate(Collection<? extends Serializable> ids) {
        return baseMapper.selectListByIdsForUpdate(ids);
    }

    @Override
    public List<HyShippingNote> getListByInvoiceId(String InoiveId) {
        return this.list(new QueryWrapper<HyShippingNote>().eq("invoice_id",InoiveId));
    }

    @Override
    public HyShippingNoteTongJiDTO sameDayList(String id, String i) {
        return baseMapper.sameDayList(id,i);
    }

    @Override
    public HyShippingNoteTongJiDTO sameDayListSql(String id, String i, String sql,String starData,String endData) {
        return baseMapper.sameDayListSql(id,i,sql,starData,endData);
    }

    @Override
    public IPage<HyShippingNoteTongJiDTO> intransitList(Page<HyShippingNoteTongJiDTO> page,QueryWrapper<HyShippingNoteTongJiDTO> queryWrapper,String id, String i) {
        return baseMapper.intransitList(page,queryWrapper,id,i);
    }

    @Override
    public List<HyShippingNoteTongJiDTO> sameDayList2(String id, String s) {
        return baseMapper.sameDayList2(id,s);
    }

    @Override
    public List<HyShippingNoteTongJiDTO> sameDayList2Sql(String id, String s, String sql) {
        return baseMapper.sameDayList2Sql(id,s,sql);
    }

    @Override
    public List<HyShippingNote> signedList(String id, String orderId) {
        return baseMapper.signedList(id,orderId);
    }

    @Override
    public  IPage<HyShippingNoteDTO> tongjiList(Page<HyShippingNoteTongJiDTO> page,QueryWrapper<HyShippingNoteTongJiDTO> queryWrapper,String s, String id, String orderId,String sql) {
        return baseMapper.tongjiList(page,queryWrapper,s,id,orderId,sql);
    }

    @Override
    public IPage<HyShippingNoteDTO> tongjiRqList(Page<HyShippingNoteTongJiDTO> page, QueryWrapper<HyShippingNoteTongJiDTO> queryWrapper, String s, String id, String orderId, String star, String end) {
        return baseMapper.tongjiRqList(page,queryWrapper,s,id,orderId,star,end);
    }

    @Override
    public IPage<HyShippingNoteTongJiDTO> sameDayList2SqlW(Page<HyShippingNoteTongJiDTO> page,QueryWrapper<HyShippingNoteTongJiDTO> queryWrapper, String customerId,String sql,String starData,String endData) {
        return baseMapper.sameDayList2SqlW(page,queryWrapper,customerId,sql,starData,endData);
    }

    @Override
    public BigDecimal getDriverDjsFeeByDriverId(String driverId) {
        return baseMapper.getDriverDjsFeeByDriverId(driverId);
    }

    @Override
    public BigDecimal getDriverTotalFeeByDriverIdAndChannel(String driverId , String payChannel) {
        return baseMapper.getDriverTotalFeeByDriverIdAndChannel(driverId , payChannel);
    }

    @Override
    public BigDecimal getCustomerDjsFee(String customerId) {
        return baseMapper.getCustomerDjsFee(customerId);
    }

    @Override
    public BigDecimal getCustomerTotalFeeByChannel(String customerId, String channelType) {
        return baseMapper.getCustomerTotalFeeByChannel(customerId , channelType);
    }

    @Override
    public BigDecimal getTotalCostPayShipping(String companyId, String channelType){
        return baseMapper.getTotalCostPayShipping(companyId, channelType);
    }

    @Override
    public BigDecimal getTotalCostService(String companyId, String channelType) {
        return baseMapper.getTotalCostService(companyId, channelType);
    }

    @Override
    public HyShippingNote getByShippingNoteNumer(String shippingNoteNumber) {
        return this.getOne(new QueryWrapper<HyShippingNote>().eq("shipping_note_number" , shippingNoteNumber));
    }

    @Override
    public List<ShippingVo> getLuXian(String startMonth, String endMonth, String id) {
        return baseMapper.getLuXian( startMonth, endMonth,id);
    }
    @Override
    public List<ShippingVo> getLuXian2(String startMonth, String endMonth, String id) {
        return baseMapper.getLuXian2( startMonth, endMonth,id);
    }

    @Override
    public List<ShippingVo> getLuXianName() {
        return baseMapper.getLuXianName( );
    }

    @Override
    public boolean checkIsPay(HyShippingNote shippingNote) {
        if (shippingNote == null) {
            return false;
        }
        String shippingPayStatus = shippingNote.getShippingPayStatus();
        if ("5".equals(shippingPayStatus) || "6".equals(shippingPayStatus) || "7".equals(shippingPayStatus)) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public Result jiedan(HyShippingNote shippingNote , String vehicleId) {

        String driverId = shippingNote.getDriverId();
        //检查司机是否有正在进行的运单，是否可接单
        boolean driverMultipleOrders = HyCfgUtil.isUsed2("driver_multiple_orders");
        if(!driverMultipleOrders){
            int shippingNoteTotal = hyDriverService.getCurrentShippingNoteCount(driverId);
            if (shippingNoteTotal >= 1 ) {
                return Result.error("当前有没完成的运单,不能再接单");
            }
        }

        //检查车辆是否属于司机
        if(!hyDriverService.checkIsDriverVehicle(driverId , vehicleId)){
            return Result.error("该车辆不属于司机");
        }
        //todo 运输协议

        shippingNote.setShippingStatus(ShippingStatus.已接单.getValue());
        shippingNote.setStatusDtReceive(new Date());//接单时间
        shippingNote.setVehicleId(vehicleId);

        //陆交开放平台 创建运单条件：司机和车辆同时上传成功
        HyVehicle hyVehicle = this.vehicleService.getById(vehicleId);
        if (HyCfgUtil.isUsed2("liaoning_tax_report")) {
            HyCompanyConfig hyCompanyConfig = this.companyConfigService.getByCompanyId(shippingNote.getCompanyId());
            log.info("校验辽宁税务司机、车辆，{} - {} - {} - {}", shippingNote.getCompanyId(), hyCompanyConfig.getTaxUploadType(), shippingNote.getShippingNoteNumber(), hyVehicle.getLnTaxUploadStatus());
            if (3 == hyCompanyConfig.getTaxUploadType().intValue()) {
                if (!shippingNote.getAlctIdentification().equals("1")) {
                    return Result.error("该运单税务创建状态错误");
                }

                if (StringUtils.isNotEmpty(hyVehicle.getLnTaxUploadStatus())) {

                    boolean bVehicle = hyVehicle.getLnTaxUploadStatus().startsWith("1");
                    if (bVehicle) {
                        Result r = this.shippingNoteApiAlct56Service.createShippingNote(shippingNote);
                        if (!r.getCode().equals(CommonConstant.SC_OK_200)) {
                            return Result.error("税务系统返回错误: " + r.getMessage());
                        }
                    } else {
                        return Result.error("车辆税务上报状态错误,请先上报数据");
                    }

//                List<String> vehicleSt = Arrays.asList(hyVehicle.getLnTaxUploadStatus().split("\\|")).stream().distinct().collect(
//                        Collectors.toList());
//                if (vehicleSt.size() == 1) {
//                    Result r = this.shippingNoteApiAlct56Service.createShippingNote(shippingNote);
//                    if (!r.getCode().equals(CommonConstant.SC_OK_200)) {
//                        return Result.error(r.getMessage());
//                    }
//                } else {
//                    return Result.error("车辆税务上报状态错误,请先上报数据");
//                }
                } else {
                    return Result.error("车辆数据未上报辽宁税务");
                }
            }
        }

        if (HyCfgUtil.isUsed2("ordos_report")) {
            HyCompanyConfig hyCompanyConfig = this.companyConfigService.getByCompanyId(shippingNote.getCompanyId());
            log.info("校验鄂尔多斯市上报司机、车辆，{} - {} - {} - {}", shippingNote.getCompanyId(), hyCompanyConfig.getParkReportPlatformType(), shippingNote.getShippingNoteNumber(), hyVehicle.getZjUploadStatus());
            if (hyCompanyConfig.getParkReportPlatformType().intValue() == 200) {

                if (!"1".equals(hyVehicle.getZjUploadStatus())) {
                    return Result.error("车辆数据未上报鄂尔多斯市监管平台");
                }
            }
        }

        this.updateById(shippingNote);
        return Result.OK("操作成功");
    }


    @Override
    @Transactional
    public Result zybpaidan(ZybShippingNoteVO zybVO) {

        HyOrder hyOrder = this.hyOrderService.getById(zybVO.getOrderId());
        if (null == hyOrder) {
            return Result.error("货源查找失败");
        }

        if (ObjectUtil.isEmpty(hyOrder.getTotalGoodsWeight())) {
            return Result.error("货源的货物总重量不能为空");
        }

        HyVehicle hyVehicle = this.vehicleService.getById(zybVO.getVehicleId());
        if (null == hyVehicle) {
            return Result.error("车辆信息不存在");
        }
        if (StrUtil.isEmpty(hyVehicle.getVehicleDevice())) {
            return Result.error(hyVehicle.getVehicleNumber() + ",车辆智运宝设备信息错误");
        }

//        if (ObjectUtil.isEmpty(hyOrder.getVehicleNum())) {
//            return Result.error("请设置货源的派车总数量");
//        }
//
//        if (hyOrder.getVehicleNum().intValue() > 100) {
//            return Result.error("货源的派车总数不能大于100");
//        }

        //先获取已经存在的围栏，再加上此次下方的围栏一起传给智运宝设备
        List<String> orderIds = this.zybService.getOrderIdsByDevice(hyVehicle.getVehicleDevice());
        orderIds.add(zybVO.getOrderId());

        //先终止未完成的设备围栏信息
        //this.zybService.cancelAutoShippingFence(hyVehicle.getVehicleDevice());

        List<HyCustomerAddressSendZybDTO> zybSendShippingFence = new ArrayList<>();
        List<HyCustomerAddressRecvZybDTO> zybRecvShippingFence = new ArrayList<>();
        for (String orderId : orderIds) {
            //根据orderID取电子围栏信息
            HyCustomerAddressSend sendShippingFence = this.hyOrderSendAddressService.getShippingFenceByOrderId(orderId);
            List<HyCustomerAddressReceive> recvShippingFence = this.hyOrderReceiveAddressService.getShippingFenceByOrderId(orderId);

            HyCustomerAddressSendZybDTO hyCustomerAddressSendZybDTO = new HyCustomerAddressSendZybDTO();
            BeanUtil.copyProperties(sendShippingFence, hyCustomerAddressSendZybDTO, true);
            hyCustomerAddressSendZybDTO.setOrderId(orderId);
            zybSendShippingFence.add(hyCustomerAddressSendZybDTO);

            recvShippingFence.stream().forEach(s->{
                HyCustomerAddressRecvZybDTO hyCustomerAddressRecvZybDTO = new HyCustomerAddressRecvZybDTO();
                BeanUtil.copyProperties(s, hyCustomerAddressRecvZybDTO, true);
                hyCustomerAddressRecvZybDTO.setOrderId(orderId);
                zybRecvShippingFence.add(hyCustomerAddressRecvZybDTO);
            });
        }

        //调用智运宝接口设置电子围栏
        ShippingFenceDTO shippingFenceDTO = ShippingFenceDTO.builder()
                //.shippingNoteNumber(hyShippingNote.getShippingNoteNumber())
                .device(hyVehicle.getVehicleDevice())
                .vehicleNumber(hyVehicle.getVehicleNumber())
                .build();
        Result result = this.zybService.autoSetShippingFence503New(
                shippingFenceDTO,
                zybSendShippingFence,
                zybRecvShippingFence
        );
        if (!result.getCode().equals(CommonConstant.SC_OK_200)) {
            throw new RuntimeException(result.getMessage());
        }

        HyZybStatus hyZybStatus = HyZybStatus.builder()
                .vehicleDevice(hyVehicle.getVehicleDevice())
                .orderId(hyOrder.getId())
                .orderNum(hyOrder.getOrderNum())
                .vehicleId(hyVehicle.getId())
                .shippingStatus(ShippingStatus.已接单.getValue())
                .updateTime(new Date())
                .build();
        if (this.zybService.isExistInThisOrder(hyVehicle.getVehicleDevice(), hyVehicle.getId(), hyOrder.getId())) {
            this.zybService.update(new LambdaUpdateWrapper<HyZybStatus>()
                    .eq(HyZybStatus::getVehicleDevice, hyVehicle.getVehicleDevice())
                    .eq(HyZybStatus::getOrderId, hyOrder.getId())
                    .set(HyZybStatus::getVehicleId, hyVehicle.getId()));
        } else {
            this.zybService.save(hyZybStatus);
            log.info("更新智运宝状态表,{}", JSONUtil.toJsonStr(hyZybStatus));
        }

        return Result.OK();
    }


//    @Override
//    @Transactional
//    public Result zybpaidan(ZybShippingNoteVO zybVO) {
//
//        HyOrder hyOrder = this.hyOrderService.getById(zybVO.getOrderId());
//        if (null == hyOrder) {
//            return Result.error("货源查找失败");
//        }
//
//        HyVehicle hyVehicle = this.vehicleService.getById(zybVO.getVehicleId());
//        if (null == hyVehicle || StrUtil.isEmpty(hyVehicle.getVehicleDevice())) {
//            return Result.error("车辆绑定智运宝设备出现错误");
//        }
//
//        if (ObjectUtil.isEmpty(hyOrder.getVehicleNum())) {
//            return Result.error("请设置货源的派车总数量");
//        }
//
//        if (hyOrder.getVehicleNum().intValue() > 100) {
//            return Result.error("货源的派车总数不能大于100");
//        }
//
////        HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(hyOrder.getCustomerId());
////        if (customerCompany == null) {
////            return Result.error("未找到货主签约信息");
////        }
////        String companyId = customerCompany.getCompanyId();
////
////        HyShippingNote hyShippingNote = addByOrder(hyOrder, null, companyId);
////        hyShippingNote.setVehicleId(hyVehicle.getId());
////        hyShippingNote.setVehicleDevice(hyVehicle.getVehicleDevice());
////        hyShippingNote.setShippingStatus(ShippingStatus.已接单.getValue());
//        //保存运单信息
//        //this.save(hyShippingNote);
//
//        if (this.zybService.isExistInThisOrder(hyVehicle.getVehicleDevice(), hyVehicle.getVehicleNumber(), hyOrder.getId())) {
//            log.info("在该货源下已派单,{} -> {}", hyVehicle.getVehicleNumber(), hyVehicle.getVehicleDevice());
//            return Result.OK(hyVehicle.getVehicleNumber() + " 在该货源下已派单");
//        }
//
//        //先终止未完成的设备围栏信息
//        this.zybService.cancelAutoShippingFence(hyVehicle.getVehicleDevice());
//
//        //根据orderID取电子围栏信息
//        HyCustomerAddressSend sendShippingFence = this.hyOrderSendAddressService.getShippingFenceByOrderId(zybVO.getOrderId()).get(0);
//        List<HyCustomerAddressReceive> recvShippingFence = this.hyOrderReceiveAddressService.getShippingFenceByOrderId(zybVO.getOrderId());
//        //调用智运宝接口设置电子围栏
//        ShippingFenceDTO shippingFenceDTO = ShippingFenceDTO.builder()
//                //.shippingNoteNumber(hyShippingNote.getShippingNoteNumber())
//                .device(hyVehicle.getVehicleDevice())
//                .vehicleNumber(hyVehicle.getVehicleNumber())
//                .build();
//        Result result = this.zybService.autoSetShippingFence(
//                shippingFenceDTO,
//                sendShippingFence,
//                recvShippingFence,
//                zybVO.getOrderId(),
//                hyOrder.getOrderNum()
//        );
//        if (CommonConstant.SC_OK_200 != result.getCode()) {
//            throw new RuntimeException(result.getMessage());
//        }
//
//        HyZybStatus hyZybStatus = HyZybStatus.builder()
//                .vehicleDevice(hyVehicle.getVehicleDevice())
//                .orderId(hyOrder.getId())
//                .orderNum(hyOrder.getOrderNum())
//                .vehicleId(hyVehicle.getId())
//                .shippingStatus(ShippingStatus.已接单.getValue())
//                .updateTime(new Date())
//                .build();
//        this.zybService.saveOrUpdate(hyZybStatus);
//        log.info("更新智运宝状态表,{}", JSONUtil.toJsonStr(hyZybStatus));
//
//        return Result.OK();
//    }

    @Override
    @Transactional
    public Result zybComplete(ZybShippingNoteVO zybVO) {

        log.info("智运宝补全信息参数, {}", JSONUtil.toJsonStr(zybVO));
        if (StrUtil.isEmpty(zybVO.getTotalWeight())) {
            return Result.error("运单量不能为空");
        }

        HyDriver hyDriver = this.hyDriverService.getDriverById(zybVO.getDriverId());
        if (null == hyDriver) {
            return Result.error("实际承运人信息查找失败");
        }

        if (StrUtil.isEmpty(zybVO.getCostPayShipping())) {
            return Result.error("运费不能为空");
        }

        HyDriverBank driverBank = this.driverBankService.getDefaultDriverBank(hyDriver.getId());
        if (null == driverBank) {
            return Result.error("实际承运人银行卡信息查找失败");
        }

        HyDriver actualDriver = this.driverService.getDriverById(zybVO.getActualDriverId());
        if (null == actualDriver) {
            return Result.error("司机信息查找失败");
        }

        if (0 == this.count(new LambdaQueryWrapper<HyShippingNote>().eq(HyShippingNote::getId, zybVO.getShippingId()))) {
            return Result.error("运单信息查找失败");
        }

        //补全信息时计算司机费用，就是输入的运费
        HyShippingNote hyShippingNote = this.getById(zybVO.getShippingId());
        hyShippingNote.setPayDtCheck(new Date());//对账完成时间
        if(ObjectUtil.isNull(hyShippingNote.getShippingUnitPrice())){
            hyShippingNote.setShippingUnitPrice(BigDecimal.ZERO);
        }
        if (ObjectUtil.isNull(hyShippingNote.getLossGoodsUnitPrice())) {
            hyShippingNote.setLossGoodsUnitPrice(BigDecimal.ZERO);
        }
        if (ObjectUtil.isNull(hyShippingNote.getLossProportion())) {
            hyShippingNote.setLossProportion(BigDecimal.ZERO);
        }
        if (ObjectUtil.isNull(hyShippingNote.getGoodsWeightLoading())) {
            hyShippingNote.setGoodsWeightLoading(BigDecimal.ZERO);
        }
        if (ObjectUtil.isNull(hyShippingNote.getGoodsWeightUnloading())) {
            hyShippingNote.setGoodsWeightUnloading(BigDecimal.ZERO);
        }

        //装货量、卸货量
        hyShippingNote.setGoodsWeightLoading(new BigDecimal(zybVO.getTotalWeight()));
        hyShippingNote.setGoodsWeightUnloading(new BigDecimal(zybVO.getTotalWeight()));

        //司机运费
        hyShippingNote.setCostPay(new BigDecimal(zybVO.getCostPayShipping()));
        hyShippingNote.setCostPayShipping(new BigDecimal(zybVO.getCostPayShipping()));
        hyShippingNote.setCostPayTotal(new BigDecimal(zybVO.getCostPayShipping()));
        hyShippingNote.setCostService(BigDecimal.ZERO);
        hyShippingNote.setCostServicePercent(BigDecimal.ZERO);
        hyShippingNote.setDriverMlWs(zybVO.getCostPayShipping());
        hyShippingNote.setDriverFee(new BigDecimal(zybVO.getCostPayShipping()));
        hyShippingNote.setCustomerFee(new BigDecimal(zybVO.getCostPayShipping()));
        hyShippingNote.setShippingStatus(ShippingStatus.已签收.getValue());
        hyShippingNote.setShippingPayStatus("4");
        hyShippingNote.setStatusDtSign(new Date());

        //实际承运人信息
        hyShippingNote.setDriverId(hyDriver.getId());
        hyShippingNote.setDriverBankId(driverBank.getId());
        //司机信息
        hyShippingNote.setActualDriverId(actualDriver.getId());

        boolean bUpdate = this.updateById(hyShippingNote);
        log.warn("运单信息补全更新, {}", hyShippingNote);
        if (!bUpdate) {
            throw new RuntimeException("运单信息更新失败");
        }

        HyBill hyBill = billService.createBill(hyShippingNote, BillTypeEnum.PAY ,null, "4");
        if (!hyBillService.saveOrUpdate(hyBill)) {
            throw new RuntimeException("保存账单失败");
        }

        //检查运单补全信息状态，如果都补全了要完结货源
        //这里不需要判断返回值，有问题手工进行运单完结
        this.checkForOrderTransport(hyShippingNote.getOrderId());

        return Result.OK("操作成功");
    }


    @Override
    public Result zybTrigger(ShippingFenceTriggerDTO shippingFenceTriggerDTO) {

        log.info("触发智运宝设备围栏 -> {}", JSONUtil.toJsonStr(shippingFenceTriggerDTO));

        String zybShippingNumber = shippingFenceTriggerDTO.getShippingNoteNumber();
        String vehicleDevice = shippingFenceTriggerDTO.getDevice();

        for (FenceTriggerDTO fenceTriggerDTO : shippingFenceTriggerDTO.getFenceTriggerList()) {

            int shippingFenceType = fenceTriggerDTO.getFenceType();
            //触发装货围栏
            //运单状态 1已接单 2装货中 3运输中 4已交货 5已签收
            if (ZybShippingTypeEnum.装货围栏.getValue().intValue() == shippingFenceType) {
                String orderId = fenceTriggerDTO.getRemark();
                HyOrder hyOrder = this.hyOrderService.getById(orderId);
                if (null == hyOrder) {
                    log.warn("货源查找失败--- {}", JSONUtil.toJsonStr(fenceTriggerDTO));
                    return Result.error("货源查找失败");
                }

                HyVehicle hyVehicle = this.vehicleService.getOne(new LambdaQueryWrapper<HyVehicle>().eq(HyVehicle::getVehicleDevice, vehicleDevice));
                if (null == hyVehicle || StrUtil.isEmpty(hyVehicle.getVehicleDevice())) {
                    log.warn("车辆绑定智运宝设备出现错误--- {}", JSONUtil.toJsonStr(fenceTriggerDTO));
                    return Result.error("车辆绑定智运宝设备出现错误");
                }

                HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(hyOrder.getCustomerId());
                if (customerCompany == null) {
                    log.warn("未找到货主签约信息--- {}", JSONUtil.toJsonStr(fenceTriggerDTO));
                    return Result.error("未找到货主签约信息");
                }

                String companyId = customerCompany.getCompanyId();

                HyShippingNote hyShippingNote = addByOrder(hyOrder, null, companyId);
                hyShippingNote.setVehicleId(hyVehicle.getId());
                hyShippingNote.setVehicleDevice(hyVehicle.getVehicleDevice());
                hyShippingNote.setShippingStatus(ShippingStatus.运输中.getValue());
                hyShippingNote.setZybShippingNumber(zybShippingNumber);
                hyShippingNote.setStatusDtLoading(new Date());

                //TODO 智运宝运单的收发货地址没有写到表里
                //保存运单信息
                this.save(hyShippingNote);
                log.info("智运宝创建运单{} - {} - {}成功，围栏状态{}",
                        hyShippingNote.getShippingNoteNumber(),zybShippingNumber, vehicleDevice, shippingFenceType);
            }

            //触发卸货围栏
            if (ZybShippingTypeEnum.卸货围栏.getValue().intValue() == shippingFenceType) {

                String address = fenceTriggerDTO.getAddress();
                String orderId = fenceTriggerDTO.getRemark().split("_")[0];
                String addressId = fenceTriggerDTO.getRemark().split("_")[1];

                //Modified at 2023-07-17 for 只要触发了卸货围栏，就结束该设备的运单，视为一次正常的装卸货
                HyShippingNote hyShippingNote = this.getOne(new LambdaQueryWrapper<HyShippingNote>()
                        .eq(HyShippingNote::getVehicleDevice, vehicleDevice)
                        .orderByDesc(HyShippingNote::getStatusDtLoading)
                        .last("LIMIT 1"));
                if (null == hyShippingNote) {
                    log.error("记录异常日志 ------ {}",vehicleDevice);
                    return Result.OK();
                }
//                HyShippingNote hyShippingNote = this.getOne(new LambdaQueryWrapper<HyShippingNote>().eq(HyShippingNote::getZybShippingNumber, zybShippingNumber));
//                if (!hyShippingNote.getOrderId().equals(orderId)) {
//                    log.warn("智运宝运单{} - {} - {} - {}触发了其它货源的收货围栏，直接抛弃",
//                            hyShippingNote.getShippingNoteNumber(), vehicleDevice, hyShippingNote.getOrderId(), JSONUtil.toJsonStr(fenceTriggerDTO));
//                    return Result.OK();
//                }

                if (3 < Integer.valueOf(hyShippingNote.getShippingStatus())) {
                    log.warn("智运宝运单{} - {} - {}已交货或签收，卸货电子围栏无效",
                            hyShippingNote.getShippingNoteNumber(), zybShippingNumber, vehicleDevice);
                    return Result.OK();
                }
                //设置已收货状态
                if (!this.updateStatusByZybShippingNumber(hyShippingNote.getShippingNoteNumber(), ShippingStatus.已交货.getValue(), new Date(), address, addressId)) {
                    log.error("智运宝运单{} - {} - {}设置卸货状态异常！",
                            hyShippingNote.getShippingNoteNumber(), zybShippingNumber, vehicleDevice);
                    return Result.error("运单设置卸货状态异常");
                }
                log.info("智运宝更新运单{} - {} - {}成功，收货围栏状态{}",
                        hyShippingNote.getShippingNoteNumber(), zybShippingNumber, vehicleDevice, shippingFenceType);
            }
        }

        return Result.OK();
    }


//    @Override
//    public Result zybTrigger(ShippingFenceTriggerDTO shippingFenceTriggerDTO) {
//
//        int shippingFenceType = shippingFenceTriggerDTO.getFenceTriggerList().get(0).getFenceType();
//        String zybShippingNumber = shippingFenceTriggerDTO.getShippingNoteNumber();
//        String vehicleDevice = shippingFenceTriggerDTO.getDevice();
//        //触发装货围栏
//        //运单状态 1已接单 2装货中 3运输中 4已交货 5已签收
//        if (ZybShippingTypeEnum.装货围栏.getValue().intValue() == shippingFenceType) {
//            String orderId = shippingFenceTriggerDTO.getFenceTriggerList().get(0).getRemark();
//            HyOrder hyOrder = this.hyOrderService.getById(orderId);
//            if (null == hyOrder) {
//                return Result.error("货源查找失败");
//            }
//
//            HyVehicle hyVehicle = this.vehicleService.getOne(new LambdaQueryWrapper<HyVehicle>().eq(HyVehicle::getVehicleDevice, vehicleDevice));
//            if (null == hyVehicle || StrUtil.isEmpty(hyVehicle.getVehicleDevice())) {
//                return Result.error("车辆绑定智运宝设备出现错误");
//            }
//
//            HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(hyOrder.getCustomerId());
//            if (customerCompany == null) {
//                return Result.error("未找到货主签约信息");
//            }
//            String companyId = customerCompany.getCompanyId();
//
//            HyShippingNote hyShippingNote = addByOrder(hyOrder, null, companyId);
//            hyShippingNote.setVehicleId(hyVehicle.getId());
//            hyShippingNote.setVehicleDevice(hyVehicle.getVehicleDevice());
//            hyShippingNote.setShippingStatus(ShippingStatus.运输中.getValue());
//            hyShippingNote.setZybShippingNumber(zybShippingNumber);
//            hyShippingNote.setStatusDtLoading(new Date());
//
//            //TODO 智运宝运单的收发货地址没有写到表里
//            //保存运单信息
//            this.save(hyShippingNote);
//            log.info("智运宝创建运单{} - {} - {}成功，围栏状态{}",
//                    hyShippingNote.getShippingNoteNumber(),zybShippingNumber, vehicleDevice, shippingFenceType);
//        }
//
//        //触发卸货围栏
//        if (ZybShippingTypeEnum.卸货围栏.getValue().intValue() == shippingFenceType) {
//            HyShippingNote hyShippingNote = this.getOne(new LambdaQueryWrapper<HyShippingNote>().eq(HyShippingNote::getZybShippingNumber, zybShippingNumber));
//            if (3 < Integer.valueOf(hyShippingNote.getShippingStatus())) {
//                log.warn("智运宝运单{} - {} - {}已交货或签收，卸货电子围栏无效",
//                        hyShippingNote.getShippingNoteNumber(), zybShippingNumber, vehicleDevice);
//                return Result.OK();
//            }
//            //设置已收货状态
//            String address = shippingFenceTriggerDTO.getFenceTriggerList().get(0).getAddress();
//            String addressId = shippingFenceTriggerDTO.getFenceTriggerList().get(0).getRemark();
//            if (!this.updateStatusByZybShippingNumber(hyShippingNote.getShippingNoteNumber(), ShippingStatus.已交货.getValue(), new Date(), address, addressId)) {
//                log.error("智运宝运单{} - {} - {}设置卸货状态异常！",
//                        hyShippingNote.getShippingNoteNumber(), zybShippingNumber, vehicleDevice);
//                return Result.error("运单设置卸货状态异常");
//            }
//            log.info("智运宝更新运单{} - {} - {}成功，收货围栏状态{}",
//                    hyShippingNote.getShippingNoteNumber(), zybShippingNumber, vehicleDevice, shippingFenceType);
//        }
//
//        return Result.OK();
//    }


    private void checkForOrderTransport(String orderId) {

        HyOrder hyOrder = this.hyOrderService.getById(orderId);
        if (ObjectUtil.isNotNull(hyOrder.getVehicleNum()) && hyOrder.getVehicleNum() > 0) {

            BigDecimal totalNum = hyOrder.getTotalGoodsWeight();
            List<HyShippingNote> hyShippingNoteList = this.list(new LambdaQueryWrapper<HyShippingNote>()
                    .eq(HyShippingNote::getOrderId, orderId)
                    .eq(HyShippingNote::getShippingStatus, ShippingStatus.已签收.getValue()));

            BigDecimal finishedNum = hyShippingNoteList.stream().map(s->s.getGoodsWeightUnloading()).reduce(BigDecimal::add).get();

            log.warn("智运宝检查货源已完结运单,货源ID {}, {} -> {}", orderId, totalNum, finishedNum);
            //运单当前已完成总数 大于等于 货源指定的总吨数时，完结货源
            if (finishedNum.compareTo(totalNum) > -1) {
                this.orderService.zybOrderFinish(hyOrder);
            }
        } else {
            log.warn("智运宝记录货源车辆总数错误, {}", orderId);
        }

        return;
    }

    @Override
    public boolean updateStatusByZybShippingNumber(String shippingNumber, String status, Date recvTime, String recvAddress, String recvAddressId) {
        return this.update(new LambdaUpdateWrapper<HyShippingNote>()
                .eq(HyShippingNote::getShippingNoteNumber, shippingNumber)
                .set(HyShippingNote::getShippingStatus, status)
                .set(ObjectUtil.isNotNull(recvTime), HyShippingNote::getStatusDtReceive, recvTime)
                .set(ObjectUtil.isNotNull(recvTime), HyShippingNote::getStatusDtUnloading, recvTime)
                .set(StrUtil.isNotEmpty(recvAddress), HyShippingNote::getReceiveAddress, recvAddress)
                .set(StrUtil.isNotEmpty(recvAddressId), HyShippingNote::getAddressReceiveId, recvAddressId)
        );
    }


    @Override
    public String getDriverFeeSum(String driverId) {
        return baseMapper.getDriverFeeSum(driverId);
    }

    @Override
    public Map<String, Map<String,BigDecimal>> getCurMonthDriverFee(String driverId) {
        return baseMapper.getCurMonthDriverFee(driverId);
    }

    @Override
    public Map<String, Map<String,BigDecimal>> getCurMonthDriversFee(Collection<? extends Serializable> driverIds) {
        Map<String, Map<String,BigDecimal>> curMonthDriversFee = baseMapper.getCurMonthDriversFee(driverIds);
        return curMonthDriversFee;
    }

    @Override
    public List<ShuiWuExportShippingNoteDTO> guoShuiShippingExport(QueryWrapper<HyShippingNoteDTO> queryWrapper) {
        return baseMapper.guoShuiShippingExport(queryWrapper);
    }

    @Override
    @Transactional
    public Result saveInsurance(InsuranceApplyDto insuranceApplyDto) {

        log.error("保存保险单{}", JSONUtil.toJsonStr(insuranceApplyDto));
        //保存保险单信息  1、保险公司 2、保险公司代码 3、保单号 4、保单路径
        InsuranceApplyRecord insuranceApplyRecord = InsuranceApplyRecord.builder()
                .insuranceCompany(insuranceApplyDto.getInsuranceCompany())
                .insuranceCompanyNumber(insuranceApplyDto.getInsuranceNumber())
                .insurancePolicy(insuranceApplyDto.getInsurancePolicy())
                .pdfUrl(insuranceApplyDto.getPdfUrl())
                .build();
        this.insuranceApplyRecordService.save(insuranceApplyRecord);

        //将保单号保存到运单表中
        boolean bUpdate = this.update(new LambdaUpdateWrapper<HyShippingNote>()
                .eq(HyShippingNote::getId, insuranceApplyDto.getShippingId())
                .set(HyShippingNote::getInsuranceNo, insuranceApplyRecord.getId())
        );
        if (!bUpdate) {
            throw new JeecgBootException("保单保存失败");
        }

        return Result.OK("操作成功");
    }

    @Override
    public Result previewInsurance(String insuranceId) {
        InsuranceApplyRecord insuranceApplyRecord = this.insuranceApplyRecordService.getById(insuranceId);
        return Result.OK(insuranceApplyRecord);
    }

    @Override
    public int count2(String driverId, String receiveAreaCode) {
        return baseMapper.count2(driverId,receiveAreaCode);
    }

    @Override
    public void ModifyFreightRiskControl(HyShippingNote oldShipping,HyShippingNote newShipping) {

        BigDecimal oldShippingUnitPrice = oldShipping.getShippingUnitPrice();
        BigDecimal newShippingUnitPrice = newShipping.getShippingUnitPrice();

        if(oldShippingUnitPrice!=null && newShippingUnitPrice!=null){
            BigDecimal abs = oldShippingUnitPrice.divide(newShippingUnitPrice,2,BigDecimal.ROUND_HALF_UP);
            int flag = abs.compareTo(new BigDecimal(1.25));
            if(flag==1){
                newShipping.setModifyFreightStatus("1");
            }
        }


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HyOrder saveOrder(HyShippingNoteAndOrder hyShippingNote, HyCustomer customer, HyCustomerCompany hyCustomerCompany) {
        HyOrder hyOrderDTO = new HyOrder();
        HyCustomerAddressSend customerAddressSend = customerAddressSendService.getById(hyShippingNote.getAddressSendId());
        HyCustomerAddressReceive addressReceive = customerAddressReceiveService.getById(hyShippingNote.getAddressReceiveId());
        hyOrderDTO.setCustomerId(customer.getId());
        if (StringUtils.isNotEmpty(hyShippingNote.getKhdh())){
            hyOrderDTO.setKhdh(hyShippingNote.getKhdh());
        }
        hyOrderDTO.setOrderType("1");
        hyOrderDTO.setOrderMode(hyShippingNote.getOrderMode());
        if (StringUtils.isNotEmpty(hyShippingNote.getBusinessTypeCode())){
            hyOrderDTO.setBusinessTypeCode(hyShippingNote.getBusinessTypeCode());
        }
        hyOrderDTO.setGoodsUnit(hyShippingNote.getGoodsUnit());
        hyOrderDTO.setDescriptionOfGoods(hyShippingNote.getDescriptionOfGoods());
        hyOrderDTO.setCargoTypeClassificationCode(hyShippingNote.getCargoTypeClassificationCode());
        hyOrderDTO.setPayType(hyShippingNote.getPayType());
        if (hyShippingNote.getPayType().equals("2")){
            hyOrderDTO.setCarrierId(hyShippingNote.getCarrierId());
            hyOrderDTO.setCarrierFeeType(hyShippingNote.getCarrierFeeType());
            hyOrderDTO.setCarrierUnitFee(hyShippingNote.getCarrierUnitFee());
        }
        hyOrderDTO.setLossGoodsUnitPrice(hyShippingNote.getLossGoodsUnitPrice());
        hyOrderDTO.setShippingUnitPrice(hyShippingNote.getShippingUnitPrice());
        hyOrderDTO.setShippingType(hyShippingNote.getShippingType());
        if (StringUtils.isNotEmpty(hyShippingNote.getCustomerShippingType())){
            hyOrderDTO.setCustomerShippingType(hyShippingNote.getCustomerShippingType());
        }
        hyOrderDTO.setLossType(hyShippingNote.getLossType());
        hyOrderDTO.setLossProportion(hyShippingNote.getLossProportion());
        hyOrderDTO.setExamineStatus("1");
        hyOrderDTO.setExamineDate(new Date());
        hyOrderDTO.setOrderStatus("2");//已发布
        hyOrderDTO.setDtPublish(new Date());
        hyOrderDTO.setIzUsedGas(hyShippingNote.getIzUsedGas());
        if (hyOrderDTO.getIzUsedGas().equals("1")){
            hyOrderDTO.setGasRechargeAmount(hyShippingNote.getGasRechargeAmount());
        }
        hyOrderDTO.setOrderImportFlag("0");
        hyOrderDTO.setUnloadingFee(hyShippingNote.getUnloadingFee());
        hyOrderDTO.setInformationFee(hyShippingNote.getInformationFee());
        hyOrderDTO.setServiceFee(hyShippingNote.getServiceFee());
        if (StringUtils.isNotEmpty(hyShippingNote.getAgentId())){
            hyOrderDTO.setAgentId(hyShippingNote.getAgentId());
            hyOrderDTO.setAgentPrice(hyShippingNote.getAgentPrice());
        }
        hyOrderDTO.setCreateTime(new Date());
        hyOrderDTO.setCreateBy(userUtil.getLoginUser().getUsername());
        hyOrderDTO.setOrderSetting(false);
        hyOrderDTO.setBz(hyShippingNote.getBz());
        hyOrderDTO.setUnloadingBz(hyShippingNote.getUnloadingBz());
        if (hyShippingNote.getPayType().equals("3")){
            hyOrderDTO.setPreType(hyShippingNote.getPreType());
            hyOrderDTO.setPreUnitFee(hyShippingNote.getPreUnitFee());
        }
        if (StringUtils.isNotEmpty(hyShippingNote.getKeyword())){
            hyOrderDTO.setKeyword(hyShippingNote.getKeyword());
        }
        if (StringUtils.isNotEmpty(hyShippingNote.getIntroducer())){
            hyOrderDTO.setIntroducer(hyShippingNote.getIntroducer());
        }
        if (StringUtils.isNotEmpty(hyShippingNote.getDispatcher())){
            hyOrderDTO.setDispatcher(hyShippingNote.getDispatcher());
        }
        hyOrderDTO.setIzOrderSet("0");
        if (hyShippingNote.getIzDriverMl().equals("1")){
            hyOrderDTO.setDriverMlWs(hyShippingNote.getDriverMlWs());
            hyOrderDTO.setDriverMlWs(hyShippingNote.getDriverMlWs());
        }
        hyOrderDTO.setOrderImportFlag("2");//0正常 1模板导入2一键补单
        hyOrderDTO.setIzDriverMl(hyShippingNote.getIzDriverMl());
        hyOrderDTO.setIzZd(hyShippingNote.getIzZd());
        if (hyShippingNote.getIzZd().equals("1")){
            hyOrderDTO.setZdJs(hyShippingNote.getZdJs());
        }
        hyOrderDTO.setCostServiceId(hyCustomerCompany.getId());
        hyOrderDTO.setCostServiceId(hyShippingNote.getCustomerId());

        hyOrderDTO.setAddressSendId(hyShippingNote.getAddressSendId());
        if (hyShippingNote.getSendDate()!=null){
            hyOrderDTO.setSendDate(hyShippingNote.getSendDate());
        }
        hyOrderDTO.setSendAddressName(hyShippingNote.getSendAddressName());
        hyOrderDTO.setSendAddressName(hyShippingNote.getSendAddressName());
        hyOrderDTO.setSendLatitude(hyShippingNote.getSendLatitude());
        hyOrderDTO.setSendLongitude(hyShippingNote.getSendLongitude());
        hyOrderDTO.setSendAreaCode(hyShippingNote.getSendAreaCode());
        hyOrderDTO.setSendContactName(hyShippingNote.getSendContactName());
        hyOrderDTO.setSendContactTel(hyShippingNote.getSendContactTel());
        hyOrderDTO.setSendContactCredit(customerAddressSend.getContactCredit());



        hyOrderDTO.setAddressReceiveId(hyShippingNote.getAddressReceiveId());
        hyOrderDTO.setReceiveAddress(hyShippingNote.getReceiveAddress());
        hyOrderDTO.setReceiveAddressName(hyShippingNote.getReceiveAddressName());
        hyOrderDTO.setReceiveAreaCode(hyShippingNote.getReceiveAreaCode());
        hyOrderDTO.setReceiveContactName(hyShippingNote.getReceiveContactName());
        hyOrderDTO.setReceiveContactTel(hyShippingNote.getReceiveContactTel());
        hyOrderDTO.setReceiveLatitude(hyShippingNote.getReceiveLatitude());
        hyOrderDTO.setReceiveLongitude(hyShippingNote.getReceiveLongitude());

        if (hyShippingNote.getReceiveDate()!=null){
            hyOrderDTO.setReceiveDate(hyShippingNote.getReceiveDate());
        }
        hyOrderDTO.setReceiveContactCredit(addressReceive.getContactCredit());
        hyOrderDTO.setCreateBy(userUtil.getLoginUser().getUsername());
        hyOrderDTO.setCreateTime(new Date());



        //处理发货数据
        HyOrderSendAddress orderSendAddress = new HyOrderSendAddress();
        orderSendAddress.setAddressSendId(hyShippingNote.getAddressSendId());
        orderSendAddress.setIzDest(true);
        if (hyShippingNote.getSendDate()!=null){
            orderSendAddress.setSendDate(hyShippingNote.getSendDate());
        }
        orderSendAddress.setSendAddressName(hyShippingNote.getSendAddressName());
        orderSendAddress.setSendAddressName(hyShippingNote.getSendAddressName());
        orderSendAddress.setSendLatitude(hyShippingNote.getSendLatitude());
        orderSendAddress.setSendLongitude(hyShippingNote.getSendLongitude());
        orderSendAddress.setSendAreaCode(hyShippingNote.getSendAreaCode());
        orderSendAddress.setSendContactName(hyShippingNote.getSendContactName());
        orderSendAddress.setSendContactTel(hyShippingNote.getSendContactTel());
        orderSendAddress.setSendContactCredit(customerAddressSend.getContactCredit());
        orderSendAddress.setSortNum(1);
        orderSendAddress.setCreateBy(userUtil.getLoginUser().getUsername());
        orderSendAddress.setCreateTime(new Date());

        //处理收货数据
        HyOrderReceiveAddress receiveAddress = new HyOrderReceiveAddress();
        receiveAddress.setAddressReceiveId(hyShippingNote.getAddressReceiveId());
        receiveAddress.setIzDest(true);
        receiveAddress.setReceiveAddress(hyShippingNote.getReceiveAddress());
        receiveAddress.setReceiveAddressName(hyShippingNote.getReceiveAddressName());
        receiveAddress.setReceiveAreaCode(hyShippingNote.getReceiveAreaCode());
        receiveAddress.setReceiveContactName(hyShippingNote.getReceiveContactName());
        receiveAddress.setReceiveContactTel(hyShippingNote.getReceiveContactTel());
        receiveAddress.setReceiveLatitude(hyShippingNote.getReceiveLatitude());
        receiveAddress.setReceiveLongitude(hyShippingNote.getReceiveLongitude());

        if (hyShippingNote.getReceiveDate()!=null){
            receiveAddress.setReceiveDate(hyShippingNote.getReceiveDate());
        }
        receiveAddress.setReceiveContactCredit(addressReceive.getContactCredit());
        receiveAddress.setCreateBy(userUtil.getLoginUser().getUsername());
        receiveAddress.setCreateTime(new Date());
        receiveAddress.setSortNum(1);

        //众汇要求货源部分添加里程数
        try {
            MapDirectionDTO mapDirectionDTO = this.amapService.getEstimateMileageForOrder(hyOrderDTO);
            if (ObjectUtil.isNotEmpty(mapDirectionDTO)) {
                hyOrderDTO.setMileage(new BigDecimal(mapDirectionDTO.getDistance()));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //生成货源号
        String orderNum = codeUtil.createOrderNum();
        hyOrderDTO.setOrderNum(orderNum);
        HyOrder hyOrderNew = new HyOrder();
        BeanUtils.copyProperties(hyOrderDTO, hyOrderNew);
        hyOrderService.save(hyOrderNew);
        orderSendAddress.setOrderId(hyOrderNew.getId());
        receiveAddress.setOrderId(hyOrderNew.getId());
        hyOrderSendAddressService.save(orderSendAddress);
        hyOrderReceiveAddressService.save(receiveAddress);
        return hyOrderNew;
    }

    @Override
    public Result importUpdateShippingNote(List<ImportUpdateShippingNoteDTO> importShippingNoteDTOList) {

        //校验数据正确性
        int i = 2;
        for (ImportUpdateShippingNoteDTO dto : importShippingNoteDTOList) {
            //运单号不能为空
            if (StrUtil.isEmpty(dto.getShippingNoteNumber())) {
                throw new JeecgBootException("第" + i + "行运单号不能为空，运单号为必填项");
            }

            //处理空格
            dto.setShippingNoteNumber(dto.getShippingNoteNumber().trim());
            if (StrUtil.isNotEmpty(dto.getOrderNum())) {
                dto.setOrderNum(dto.getOrderNum().trim());
            }
            if (StrUtil.isNotEmpty(dto.getCustomerName())) {
                dto.setCustomerName(dto.getCustomerName().trim());
            }
            if (StrUtil.isNotEmpty(dto.getCompanyName())) {
                dto.setCompanyName(dto.getCompanyName().trim());
            }

            if (StrUtil.isNotEmpty(dto.getStatusDtReceive())) {
                dto.setStatusDtReceive(dto.getStatusDtReceive().trim());
                Date statusDtReceive = DateUtils.stringToDateTime(dto.getStatusDtReceive());
                if (statusDtReceive == null) {
                    throw new JeecgBootException("第" + i + "行实际接单时间不正确,应为日期时间文本格式");
                }

            }
            if (StrUtil.isNotEmpty(dto.getStatusDtLoading())) {
                dto.setStatusDtLoading(dto.getStatusDtLoading().trim());
                Date statusDtLoading = DateUtils.stringToDateTime(dto.getStatusDtLoading());
                if (statusDtLoading == null) {
                    throw new JeecgBootException("第" + i + "行实际发货时间不正确,应为日期时间文本格式");
                }
            }
            if (StrUtil.isNotEmpty(dto.getStatusDtUnloading())) {
                dto.setStatusDtUnloading(dto.getStatusDtUnloading().trim());
                Date statusDtUnloading = DateUtils.stringToDateTime(dto.getStatusDtUnloading());
                if (statusDtUnloading == null) {
                    throw new JeecgBootException("第" + i + "行实际收货时间不正确,应为日期时间文本格式");
                }
            }
            if (StrUtil.isNotEmpty(dto.getStatusDtSign())) {
                dto.setStatusDtSign(dto.getStatusDtSign().trim());
                Date statusDtSign = DateUtils.stringToDateTime(dto.getStatusDtSign());
                if (statusDtSign == null) {
                    throw new JeecgBootException("第" + i + "行实际签收时间不正确,应为日期时间文本格式");
                }
            }
            if (StrUtil.isNotEmpty(dto.getCreateTime())) {
                dto.setCreateTime(dto.getCreateTime().trim());
                Date createTime = DateUtils.stringToDateTime(dto.getCreateTime());
                if (createTime == null) {
                    throw new JeecgBootException("第" + i + "行创建时间不正确,应为日期时间文本格式");
                }
            }

            i++;
        }

        //查询公司
        List<HyCompany> companyNameList = new ArrayList<>();
        List<String> companyNames = importShippingNoteDTOList.stream().filter(item-> StrUtil.isNotEmpty(item.getCompanyName())).map(
                item -> item.getCompanyName().trim()).distinct().filter(Objects::nonNull).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(companyNames)) {
            companyNameList = this.companyService.list(new LambdaQueryWrapper<HyCompany>().in(HyCompany::getCompanyName, companyNames));
            if (companyNameList.size() != companyNames.size()) {

                List<String> dbCompanyNames = companyNameList.stream().map(
                        item -> item.getCompanyName()
                ).collect(Collectors.toList());

                String filterCompanyNames = companyNames.stream()
                        .filter(item -> !dbCompanyNames.contains(item))
                        .collect(Collectors.joining(",", "(", ")"));
                throw new JeecgBootException(filterCompanyNames + "公司信息不存在");
            }

        }

        //查询货主
        List<HyCustomer> customerNameList = new ArrayList<>();
        List<String> customerNames = importShippingNoteDTOList.stream().filter(item-> StrUtil.isNotEmpty(item.getCustomerName())).map(
                item -> item.getCustomerName().trim()).distinct().filter(Objects::nonNull).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(customerNames)) {
            customerNameList = this.customerService.list(new LambdaQueryWrapper<HyCustomer>().in(HyCustomer::getCustomerName, customerNames).eq(HyCustomer::getIzUsed, 1));
            if (customerNames.size() != customerNameList.size()) {
                List<String> dbCustomerNames = customerNameList.stream().map(
                        item -> item.getCustomerName()
                ).collect(Collectors.toList());

                String filterCustomerNames = customerNames.stream()
                        .filter(item -> !dbCustomerNames.contains(item))
                        .collect(Collectors.joining(",", "(", ")"));
                log.warn("查询到系统中已有货主数据{}, 实际导入的货主数据{}", JSONUtil.toJsonStr(dbCustomerNames), JSONUtil.toJsonStr(customerNames));
                throw new JeecgBootException(filterCustomerNames + "货主信息不存在");
            }
        }

        //查询货源
        List<HyOrder> orderNumList = new ArrayList<>();
        List<String> orderNums = importShippingNoteDTOList.stream().filter(item-> StrUtil.isNotEmpty(item.getOrderNum())).map(
                item -> item.getOrderNum().trim()).distinct().filter(Objects::nonNull).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(orderNums)) {
            orderNumList = this.orderService.list(new LambdaQueryWrapper<HyOrder>().in(HyOrder::getOrderNum, orderNums));
            if (orderNums.size() != orderNumList.size()) {
                log.warn("导入运单所属货源数大于总货源数，不匹配, {} {}", orderNums.size(), orderNumList.size());
                List<String> dbOrderNums = orderNumList.stream().map(
                        item -> item.getOrderNum()
                ).collect(Collectors.toList());

                List<String> filterOrderNums = orderNums.stream()
                        .filter(item -> !dbOrderNums.contains(item))
                        .collect(Collectors.toList());

                throw new JeecgBootException(JSONUtil.toJsonStr(filterOrderNums) + ",货源信息不存在");
            }
        }

        //查询运单
        List<String> shippingNumbers = importShippingNoteDTOList.stream().map(
                item -> item.getShippingNoteNumber().trim()).distinct().filter(Objects::nonNull).collect(Collectors.toList());

        List<HyShippingNote> shippingNoteNumberList = this.list(new LambdaQueryWrapper<HyShippingNote>().in(HyShippingNote::getShippingNoteNumber, shippingNumbers));
        if (shippingNumbers.size() != shippingNoteNumberList.size()) {
            log.warn("导入运单数量不匹配, {} {}", shippingNumbers.size(), shippingNoteNumberList.size());
            List<String> dbShippingNums = shippingNoteNumberList.stream().map(
                    item -> item.getShippingNoteNumber()
            ).collect(Collectors.toList());

            List<String> filterShippingNums = shippingNumbers.stream()
                    .filter(item -> !dbShippingNums.contains(item))
                    .collect(Collectors.toList());

            throw new JeecgBootException(JSONUtil.toJsonStr(filterShippingNums) + ",运单信息不存在");
        }

        //存的时候是匹配的ID
        Map<String, String> companyNameMaps = companyNameList.stream().collect(
                Collectors.toMap(HyCompany::getCompanyName, HyCompany::getId, (key1, key2) -> key2)
        );

        Map<String, String> customerNameMaps = customerNameList.stream().collect(
                Collectors.toMap(HyCustomer::getCustomerName, HyCustomer::getId, (key1, key2) -> key2)
        );

        Map<String, String> orderNumMaps = orderNumList.stream().collect(
                Collectors.toMap(HyOrder::getOrderNum, HyOrder::getId, (key1, key2) -> key2)
        );
//        Map<String, HyOrder> orderNumMaps = orderNumList.stream().collect(
//                Collectors.toMap(HyOrder::getOrderNum, Function.identity(), (key1, key2) -> key2)
//        );

        for (ImportUpdateShippingNoteDTO dto : importShippingNoteDTOList) {
            this.update(new LambdaUpdateWrapper<HyShippingNote>()
                    .eq(HyShippingNote::getShippingNoteNumber, dto.getShippingNoteNumber())
                    .set(StrUtil.isNotEmpty(dto.getCreateTime()), HyShippingNote::getCreateTime, DateUtils.stringToDateTime(dto.getCreateTime()))
                    .set(StrUtil.isNotEmpty(dto.getStatusDtReceive()), HyShippingNote::getStatusDtReceive, DateUtils.stringToDateTime(dto.getStatusDtReceive()))
                    .set(StrUtil.isNotEmpty(dto.getStatusDtLoading()), HyShippingNote::getStatusDtLoading, DateUtils.stringToDateTime(dto.getStatusDtLoading()))
                    .set(StrUtil.isNotEmpty(dto.getStatusDtUnloading()), HyShippingNote::getStatusDtUnloading, DateUtils.stringToDateTime(dto.getStatusDtUnloading()))
                    .set(StrUtil.isNotEmpty(dto.getStatusDtSign()), HyShippingNote::getStatusDtSign, DateUtils.stringToDateTime(dto.getStatusDtSign()))
                    .set(StrUtil.isNotEmpty(dto.getOrderNum()), HyShippingNote::getOrderId, orderNumMaps.get(dto.getOrderNum()))
                    .set(StrUtil.isNotEmpty(dto.getCustomerName()), HyShippingNote::getCustomerId, customerNameMaps.get(dto.getCustomerName()))
                    .set(StrUtil.isNotEmpty(dto.getCompanyName()), HyShippingNote::getCompanyId, companyNameMaps.get(dto.getCompanyName()))
            );
        }

        return Result.OK("批量修改运单成功");
    }

    @Override
    public Integer getCount(QueryWrapper<HyShippingNote> queryWrapper) {
        return this.baseMapper.getCount(queryWrapper);
    }

    @Override
    public Integer getZtCount(QueryWrapper<HyShippingNote> queryWrapper) {
        return this.baseMapper.getZtCount(queryWrapper);
    }

    @Override
    public List<ShuiWuExportShippingNoteDTO> guoShuiShippingExport2(QueryWrapper<HyShippingNoteDTO> queryWrapper) {
        return baseMapper.newGuoShuiShippingExport(queryWrapper);
    }


}
